class Sinatra::Helpers::Stream::Base
Constants
- URI_INSTANCE
Attributes
Public Class Methods
Sinatra::Helpers::Stream::Templates::new
# File lib/sinatra/base.rb 906 def initialize(app = nil) 907 super() 908 @app = app 909 @template_cache = Tilt::Cache.new 910 yield self if block_given? 911 end
Access settings defined with Base.set
.
# File lib/sinatra/base.rb 941 def self.settings 942 self 943 end
Private Class Methods
add a filter
# File lib/sinatra/base.rb 1368 def add_filter(type, path = /.*/, **options, &block) 1369 filters[type] << compile!(type, path, block, **options) 1370 end
Define an after filter; runs after all requests within the same context as route handlers and may access/modify the request and response.
# File lib/sinatra/base.rb 1363 def after(path = /.*/, **options, &block) 1364 add_filter(:after, path, **options, &block) 1365 end
Define a before filter; runs before all requests within the same context as route handlers and may access/modify the request and response.
# File lib/sinatra/base.rb 1356 def before(path = /.*/, **options, &block) 1357 add_filter(:before, path, **options, &block) 1358 end
Creates a Rack::Builder
instance with all the middleware set up and the given app
as end point.
# File lib/sinatra/base.rb 1502 def build(app) 1503 builder = Rack::Builder.new 1504 setup_default_middleware builder 1505 setup_middleware builder 1506 builder.run app 1507 builder 1508 end
# File lib/sinatra/base.rb 1510 def call(env) 1511 synchronize { prototype.call(env) } 1512 end
Like Kernel#caller but excluding certain magic entries and without line / method information; the resulting array contains filenames only.
# File lib/sinatra/base.rb 1516 def caller_files 1517 cleaned_caller(1).flatten 1518 end
Like caller_files
, but containing Arrays rather than strings with the first element being the file, and the second being the line.
# File lib/sinatra/base.rb 1522 def caller_locations 1523 cleaned_caller 2 1524 end
Like Kernel#caller but excluding certain magic entries
# File lib/sinatra/base.rb 1748 def cleaned_caller(keep = 3) 1749 caller(1). 1750 map! { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }. 1751 reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } } 1752 end
# File lib/sinatra/base.rb 1649 def compile(path, route_mustermann_opts = {}) 1650 Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts)) 1651 end
# File lib/sinatra/base.rb 1630 def compile!(verb, path, block, **options) 1631 # Because of self.options.host 1632 host_name(options.delete(:host)) if options.key?(:host) 1633 # Pass Mustermann opts to compile() 1634 route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze 1635 1636 options.each_pair { |option, args| send(option, *args) } 1637 1638 pattern = compile(path, route_mustermann_opts) 1639 method_name = "#{verb} #{path}" 1640 unbound_method = generate_method(method_name, &block) 1641 conditions, @conditions = @conditions, [] 1642 wrapper = block.arity != 0 ? 1643 proc { |a, p| unbound_method.bind(a).call(*p) } : 1644 proc { |a, p| unbound_method.bind(a).call } 1645 1646 [ pattern, conditions, wrapper ] 1647 end
Add a route condition. The route is considered non-matching when the block returns false.
# File lib/sinatra/base.rb 1374 def condition(name = "#{caller.first[/`.*'/]} condition", &block) 1375 @conditions << generate_method(name, &block) 1376 end
Set configuration options for Sinatra
and/or the app. Allows scoping of settings for certain environments.
# File lib/sinatra/base.rb 1434 def configure(*envs) 1435 yield self if envs.empty? || envs.include?(environment.to_sym) 1436 end
Dynamically defines a method on settings.
# File lib/sinatra/base.rb 1568 def define_singleton(name, content = Proc.new) 1569 singleton_class.class_eval do 1570 undef_method(name) if method_defined? name 1571 String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content) 1572 end 1573 end
# File lib/sinatra/base.rb 1403 def delete(path, opts = {}, &bk) route 'DELETE', path, opts, &bk end
# File lib/sinatra/base.rb 1716 def detect_rack_handler 1717 servers = Array(server) 1718 servers.each do |server_name| 1719 begin 1720 return Rack::Handler.get(server_name.to_s) 1721 rescue LoadError, NameError 1722 end 1723 end 1724 fail "Server handler (#{servers.join(',')}) not found." 1725 end
# File lib/sinatra/base.rb 1428 def development?; environment == :development end
Same as calling `set :option, false` for each of the given options.
# File lib/sinatra/base.rb 1272 def disable(*opts) 1273 opts.each { |key| set(key, false) } 1274 end
Same as calling `set :option, true` for each of the given options.
# File lib/sinatra/base.rb 1267 def enable(*opts) 1268 opts.each { |key| set(key, true) } 1269 end
Define a custom error handler. Optionally takes either an Exception class, or an HTTP status code to specify which errors should be handled.
# File lib/sinatra/base.rb 1279 def error(*codes, &block) 1280 args = compile! "ERROR", /.*/, block 1281 codes = codes.flat_map(&method(:Array)) 1282 codes << Exception if codes.empty? 1283 codes << Sinatra::NotFound if codes.include?(404) 1284 codes.each { |c| (@errors[c] ||= []) << args } 1285 end
Extension modules registered on this class and all superclasses.
# File lib/sinatra/base.rb 1212 def extensions 1213 if superclass.respond_to?(:extensions) 1214 (@extensions + superclass.extensions).uniq 1215 else 1216 @extensions 1217 end 1218 end
Force data to specified encoding. It defaults to settings.default_encoding which is UTF-8 by default
# File lib/sinatra/base.rb 1757 def self.force_encoding(data, encoding = default_encoding) 1758 return if data == settings || data.is_a?(Tempfile) 1759 if data.respond_to? :force_encoding 1760 data.force_encoding(encoding).encode! 1761 elsif data.respond_to? :each_value 1762 data.each_value { |v| force_encoding(v, encoding) } 1763 elsif data.respond_to? :each 1764 data.each { |v| force_encoding(v, encoding) } 1765 end 1766 data 1767 end
# File lib/sinatra/base.rb 1623 def generate_method(method_name, &block) 1624 define_method(method_name, &block) 1625 method = instance_method method_name 1626 remove_method method_name 1627 method 1628 end
Defining a `GET` handler also automatically defines a `HEAD` handler.
# File lib/sinatra/base.rb 1393 def get(path, opts = {}, &block) 1394 conditions = @conditions.dup 1395 route('GET', path, opts, &block) 1396 1397 @conditions = conditions 1398 route('HEAD', path, opts, &block) 1399 end
# File lib/sinatra/base.rb 1404 def head(path, opts = {}, &bk) route 'HEAD', path, opts, &bk end
Makes the methods defined in the block and in the Modules given in `extensions` available to the handlers and templates
# File lib/sinatra/base.rb 1412 def helpers(*extensions, &block) 1413 class_eval(&block) if block_given? 1414 include(*extensions) if extensions.any? 1415 end
Condition for matching host name. Parameter might be String or Regexp.
# File lib/sinatra/base.rb 1576 def host_name(pattern) 1577 condition { pattern === request.host } 1578 end
# File lib/sinatra/base.rb 1727 def inherited(subclass) 1728 subclass.reset! 1729 subclass.set :app_file, caller_files.first unless subclass.app_file? 1730 super 1731 end
Load embedded templates from the file; uses the caller's __FILE__ when no file is specified.
# File lib/sinatra/base.rb 1305 def inline_templates=(file = nil) 1306 file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file 1307 1308 begin 1309 io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file) 1310 app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2) 1311 rescue Errno::ENOENT 1312 app, data = nil 1313 end 1314 1315 if data 1316 if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m 1317 encoding = $2 1318 else 1319 encoding = settings.default_encoding 1320 end 1321 lines = app.count("\n") + 1 1322 template = nil 1323 force_encoding data, encoding 1324 data.each_line do |line| 1325 lines += 1 1326 if line =~ /^@@\s*(.*\S)\s*$/ 1327 template = force_encoding(String.new, encoding) 1328 templates[$1.to_sym] = [template, file, lines] 1329 elsif template 1330 template << line 1331 end 1332 end 1333 end 1334 end
# File lib/sinatra/base.rb 1619 def invoke_hook(name, *args) 1620 extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } 1621 end
Define the layout template. The block must return the template source.
# File lib/sinatra/base.rb 1299 def layout(name = :layout, &block) 1300 template name, &block 1301 end
# File lib/sinatra/base.rb 1407 def link(path, opts = {}, &bk) route 'LINK', path, opts, &bk end
Middleware used in this class and all superclasses.
# File lib/sinatra/base.rb 1221 def middleware 1222 if superclass.respond_to?(:middleware) 1223 superclass.middleware + @middleware 1224 else 1225 @middleware 1226 end 1227 end
Lookup or register a mime type in Rack's mime registry.
# File lib/sinatra/base.rb 1337 def mime_type(type, value = nil) 1338 return type if type.nil? 1339 return type.to_s if type.to_s.include?('/') 1340 type = ".#{type}" unless type.to_s[0] == ?. 1341 return Rack::Mime.mime_type(type, nil) unless value 1342 Rack::Mime::MIME_TYPES[type] = value 1343 end
provides all mime types matching type, including deprecated types:
mime_types :html # => ['text/html'] mime_types :js # => ['application/javascript', 'text/javascript']
# File lib/sinatra/base.rb 1348 def mime_types(type) 1349 type = mime_type type 1350 type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type] 1351 end
Create a new instance of the class fronted by its middleware pipeline. The object is guaranteed to respond to call
but may not be an instance of the class new was called on.
# File lib/sinatra/base.rb 1495 def new(*args, &bk) 1496 instance = new!(*args, &bk) 1497 Wrapper.new(build(instance).to_app, instance) 1498 end
Sugar for `error(404) { … }`
# File lib/sinatra/base.rb 1288 def not_found(&block) 1289 error(404, &block) 1290 end
# File lib/sinatra/base.rb 1405 def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end
# File lib/sinatra/base.rb 1406 def patch(path, opts = {}, &bk) route 'PATCH', path, opts, &bk end
# File lib/sinatra/base.rb 1402 def post(path, opts = {}, &bk) route 'POST', path, opts, &bk end
# File lib/sinatra/base.rb 1429 def production?; environment == :production end
The prototype instance used to process requests.
# File lib/sinatra/base.rb 1485 def prototype 1486 @prototype ||= new 1487 end
Condition for matching mimetypes. Accepts file extensions.
# File lib/sinatra/base.rb 1595 def provides(*types) 1596 types.map! { |t| mime_types(t) } 1597 types.flatten! 1598 condition do 1599 if type = response['Content-Type'] 1600 types.include? type or types.include? type[/^[^;]+/] 1601 elsif type = request.preferred_type(types) 1602 params = (type.respond_to?(:params) ? type.params : {}) 1603 content_type(type, params) 1604 true 1605 else 1606 false 1607 end 1608 end 1609 end
# File lib/sinatra/base.rb 1378 def public=(value) 1379 warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead" 1380 set(:public_folder, value) 1381 end
# File lib/sinatra/base.rb 1387 def public_dir 1388 public_folder 1389 end
# File lib/sinatra/base.rb 1383 def public_dir=(value) 1384 self.public_folder = value 1385 end
# File lib/sinatra/base.rb 1401 def put(path, opts = {}, &bk) route 'PUT', path, opts, &bk end
Stop the self-hosted server if running.
# File lib/sinatra/base.rb 1445 def quit! 1446 return unless running? 1447 # Use Thin's hard #stop! if available, otherwise just #stop. 1448 running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop 1449 $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless suppress_messages? 1450 set :running_server, nil 1451 set :handler_name, nil 1452 end
Register an extension. Alternatively take a block from which an extension will be created and registered on the fly.
# File lib/sinatra/base.rb 1419 def register(*extensions, &block) 1420 extensions << Module.new(&block) if block_given? 1421 @extensions += extensions 1422 extensions.each do |extension| 1423 extend extension 1424 extension.registered(self) if extension.respond_to?(:registered) 1425 end 1426 end
Removes all routes, filters, middleware and extension hooks from the current class (not routes/filters/… defined by its superclass).
# File lib/sinatra/base.rb 1195 def reset! 1196 @conditions = [] 1197 @routes = {} 1198 @filters = {:before => [], :after => []} 1199 @errors = {} 1200 @middleware = [] 1201 @prototype = nil 1202 @extensions = [] 1203 1204 if superclass.respond_to?(:templates) 1205 @templates = Hash.new { |hash, key| superclass.templates[key] } 1206 else 1207 @templates = {} 1208 end 1209 end
# File lib/sinatra/base.rb 1611 def route(verb, path, options = {}, &block) 1612 enable :empty_path_info if path == "" and empty_path_info.nil? 1613 signature = compile!(verb, path, block, **options) 1614 (@routes[verb] ||= []) << signature 1615 invoke_hook(:route_added, verb, path, block) 1616 signature 1617 end
Run the Sinatra
app as a self-hosted server using Thin, Puma, Mongrel, or WEBrick (in that order). If given a block, will call with the constructed handler once we have taken the stage.
# File lib/sinatra/base.rb 1459 def run!(options = {}, &block) 1460 return if running? 1461 set options 1462 handler = detect_rack_handler 1463 handler_name = handler.name.gsub(/.*::/, '') 1464 server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {} 1465 server_settings.merge!(:Port => port, :Host => bind) 1466 1467 begin 1468 start_server(handler, server_settings, handler_name, &block) 1469 rescue Errno::EADDRINUSE 1470 $stderr.puts "== Someone is already performing on port #{port}!" 1471 raise 1472 ensure 1473 quit! 1474 end 1475 end
Check whether the self-hosted server is running or not.
# File lib/sinatra/base.rb 1480 def running? 1481 running_server? 1482 end
Sets an option to the given value. If the value is a proc, the proc will be called every time the option is accessed.
# File lib/sinatra/base.rb 1231 def set(option, value = (not_set = true), ignore_setter = false, &block) 1232 raise ArgumentError if block and !not_set 1233 value, not_set = block, false if block 1234 1235 if not_set 1236 raise ArgumentError unless option.respond_to?(:each) 1237 option.each { |k,v| set(k, v) } 1238 return self 1239 end 1240 1241 if respond_to?("#{option}=") and not ignore_setter 1242 return __send__("#{option}=", value) 1243 end 1244 1245 setter = proc { |val| set option, val, true } 1246 getter = proc { value } 1247 1248 case value 1249 when Proc 1250 getter = value 1251 when Symbol, Integer, FalseClass, TrueClass, NilClass 1252 getter = value.inspect 1253 when Hash 1254 setter = proc do |val| 1255 val = value.merge val if Hash === val 1256 set option, val, true 1257 end 1258 end 1259 1260 define_singleton("#{option}=", setter) 1261 define_singleton(option, getter) 1262 define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?" 1263 self 1264 end
# File lib/sinatra/base.rb 1680 def setup_common_logger(builder) 1681 builder.use Sinatra::CommonLogger 1682 end
# File lib/sinatra/base.rb 1684 def setup_custom_logger(builder) 1685 if logging.respond_to? :to_int 1686 builder.use Rack::Logger, logging 1687 else 1688 builder.use Rack::Logger 1689 end 1690 end
# File lib/sinatra/base.rb 1653 def setup_default_middleware(builder) 1654 builder.use ExtendedRack 1655 builder.use ShowExceptions if show_exceptions? 1656 builder.use Rack::MethodOverride if method_override? 1657 builder.use Rack::Head 1658 setup_logging builder 1659 setup_sessions builder 1660 setup_protection builder 1661 end
# File lib/sinatra/base.rb 1667 def setup_logging(builder) 1668 if logging? 1669 setup_common_logger(builder) 1670 setup_custom_logger(builder) 1671 elsif logging == false 1672 setup_null_logger(builder) 1673 end 1674 end
# File lib/sinatra/base.rb 1663 def setup_middleware(builder) 1664 middleware.each { |c,a,b| builder.use(c, *a, &b) } 1665 end
# File lib/sinatra/base.rb 1676 def setup_null_logger(builder) 1677 builder.use Rack::NullLogger 1678 end
# File lib/sinatra/base.rb 1692 def setup_protection(builder) 1693 return unless protection? 1694 options = Hash === protection ? protection.dup : {} 1695 options = { 1696 img_src: "'self' data:", 1697 font_src: "'self'" 1698 }.merge options 1699 1700 protect_session = options.fetch(:session) { sessions? } 1701 options[:without_session] = !protect_session 1702 1703 options[:reaction] ||= :drop_session 1704 1705 builder.use Rack::Protection, options 1706 end
# File lib/sinatra/base.rb 1708 def setup_sessions(builder) 1709 return unless sessions? 1710 options = {} 1711 options[:secret] = session_secret if session_secret? 1712 options.merge! sessions.to_hash if sessions.respond_to? :to_hash 1713 builder.use session_store, options 1714 end
# File lib/sinatra/base.rb 1552 def setup_traps 1553 if traps? 1554 at_exit { quit! } 1555 1556 [:INT, :TERM].each do |signal| 1557 old_handler = trap(signal) do 1558 quit! 1559 old_handler.call if old_handler.respond_to?(:call) 1560 end 1561 end 1562 1563 set :traps, false 1564 end 1565 end
Starts the server by running the Rack
Handler.
# File lib/sinatra/base.rb 1529 def start_server(handler, server_settings, handler_name) 1530 # Ensure we initialize middleware before startup, to match standard Rack 1531 # behavior, by ensuring an instance exists: 1532 prototype 1533 # Run the instance we created: 1534 handler.run(self, server_settings) do |server| 1535 unless suppress_messages? 1536 $stderr.puts "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}" 1537 end 1538 1539 setup_traps 1540 set :running_server, server 1541 set :handler_name, handler_name 1542 server.threaded = settings.threaded if server.respond_to? :threaded= 1543 1544 yield server if block_given? 1545 end 1546 end
# File lib/sinatra/base.rb 1548 def suppress_messages? 1549 handler_name =~ /cgi/i || quiet 1550 end
# File lib/sinatra/base.rb 1734 def synchronize(&block) 1735 if lock? 1736 @@mutex.synchronize(&block) 1737 else 1738 yield 1739 end 1740 end
Define a named template. The block must return the template source.
# File lib/sinatra/base.rb 1293 def template(name, &block) 1294 filename, line = caller_locations.first 1295 templates[name] = [block, filename, line.to_i] 1296 end
# File lib/sinatra/base.rb 1430 def test?; environment == :test end
# File lib/sinatra/base.rb 1408 def unlink(path, opts = {}, &bk) route 'UNLINK', path, opts, &bk end
Use the specified Rack
middleware
# File lib/sinatra/base.rb 1439 def use(middleware, *args, &block) 1440 @prototype = nil 1441 @middleware << [middleware, args, block] 1442 end
Condition for matching user agent. Parameter should be Regexp. Will set params.
# File lib/sinatra/base.rb 1582 def user_agent(pattern) 1583 condition do 1584 if request.user_agent.to_s =~ pattern 1585 @params[:agent] = $~[1..-1] 1586 true 1587 else 1588 false 1589 end 1590 end 1591 end
used for deprecation warnings
# File lib/sinatra/base.rb 1743 def warn(message) 1744 super message + "\n\tfrom #{cleaned_caller.first.join(':')}" 1745 end
Public Instance Methods
Rack
call interface.
# File lib/sinatra/base.rb 914 def call(env) 915 dup.call!(env) 916 end
Forward the request to the downstream app – middleware only.
# File lib/sinatra/base.rb 971 def forward 972 fail "downstream app not set" unless @app.respond_to? :call 973 status, headers, body = @app.call env 974 @response.status = status 975 @response.body = body 976 @response.headers.merge! headers 977 nil 978 end
Exit the current block, halts any further processing of the request, and returns the specified response.
# File lib/sinatra/base.rb 958 def halt(*response) 959 response = response.first if response.length == 1 960 throw :halt, response 961 end
# File lib/sinatra/base.rb 950 def options 951 warn "Sinatra::Base#options is deprecated and will be removed, " \ 952 "use #settings instead." 953 settings 954 end
Pass control to the next matching route. If there are no more matching routes, Sinatra
will return a 404 response.
# File lib/sinatra/base.rb 966 def pass(&block) 967 throw :pass, block 968 end
Access settings defined with Base.set
.
# File lib/sinatra/base.rb 946 def settings 947 self.class.settings 948 end
Private Instance Methods
Dispatch a request with error handling.
# File lib/sinatra/base.rb 1095 def dispatch! 1096 # Avoid passing frozen string in force_encoding 1097 @params.merge!(@request.params).each do |key, val| 1098 next unless val.respond_to?(:force_encoding) 1099 val = val.dup if val.frozen? 1100 @params[key] = force_encoding(val) 1101 end 1102 1103 invoke do 1104 static! if settings.static? && (request.get? || request.head?) 1105 filter! :before 1106 route! 1107 end 1108 rescue ::Exception => boom 1109 invoke { handle_exception!(boom) } 1110 ensure 1111 begin 1112 filter! :after unless env['sinatra.static_file'] 1113 rescue ::Exception => boom 1114 invoke { handle_exception!(boom) } unless @env['sinatra.error'] 1115 end 1116 end
# File lib/sinatra/base.rb 1168 def dump_errors!(boom) 1169 msg = ["#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - #{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t") 1170 @env['rack.errors'].puts(msg) 1171 end
Find an custom error block for the key(s) specified.
# File lib/sinatra/base.rb 1153 def error_block!(key, *block_params) 1154 base = settings 1155 while base.respond_to?(:errors) 1156 next base = base.superclass unless args_array = base.errors[key] 1157 args_array.reverse_each do |args| 1158 first = args == args_array.first 1159 args += [block_params] 1160 resp = process_route(*args) 1161 return resp unless resp.nil? && !first 1162 end 1163 end 1164 return false unless key.respond_to? :superclass and key.superclass < Exception 1165 error_block!(key.superclass, *block_params) 1166 end
Run filters defined on the class and all superclasses.
# File lib/sinatra/base.rb 983 def filter!(type, base = settings) 984 filter! type, base.superclass if base.superclass.respond_to?(:filters) 985 base.filters[type].each { |args| process_route(*args) } 986 end
# File lib/sinatra/base.rb 1769 def force_encoding(*args) settings.force_encoding(*args) end
Error handling during requests.
# File lib/sinatra/base.rb 1119 def handle_exception!(boom) 1120 if error_params = @env['sinatra.error.params'] 1121 @params = @params.merge(error_params) 1122 end 1123 @env['sinatra.error'] = boom 1124 1125 if boom.respond_to? :http_status 1126 status(boom.http_status) 1127 elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599 1128 status(boom.code) 1129 else 1130 status(500) 1131 end 1132 1133 status(500) unless status.between? 400, 599 1134 1135 boom_message = boom.message if boom.message && boom.message != boom.class.name 1136 if server_error? 1137 dump_errors! boom if settings.dump_errors? 1138 raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler 1139 elsif not_found? 1140 headers['X-Cascade'] = 'pass' if settings.x_cascade? 1141 body boom_message || '<h1>Not Found</h1>' 1142 elsif bad_request? 1143 body boom_message || '<h1>Bad Request</h1>' 1144 end 1145 1146 res = error_block!(boom.class, boom) || error_block!(status, boom) 1147 return res if res or not server_error? 1148 raise boom if settings.raise_errors? or settings.show_exceptions? 1149 error_block! Exception, boom 1150 end
Run the block with 'throw :halt' support and apply result to the response.
# File lib/sinatra/base.rb 1079 def invoke 1080 res = catch(:halt) { yield } 1081 1082 res = [res] if Integer === res or String === res 1083 if Array === res and Integer === res.first 1084 res = res.dup 1085 status(res.shift) 1086 body(res.pop) 1087 headers(*res) 1088 elsif res.respond_to? :each 1089 body res 1090 end 1091 nil # avoid double setting the same response tuple twice 1092 end
If the current request matches pattern and conditions, fill params with keys and call the given block. Revert params afterwards.
Returns pass block.
# File lib/sinatra/base.rb 1021 def process_route(pattern, conditions, block = nil, values = []) 1022 route = @request.path_info 1023 route = '/' if route.empty? and not settings.empty_path_info? 1024 route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/') 1025 return unless params = pattern.params(route) 1026 1027 params.delete("ignore") # TODO: better params handling, maybe turn it into "smart" object or detect changes 1028 force_encoding(params) 1029 @params = @params.merge(params) if params.any? 1030 1031 regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? {|subpattern| subpattern.is_a?(Mustermann::Regular)} ) 1032 if regexp_exists 1033 captures = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c } 1034 values += captures 1035 @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty? 1036 else 1037 values += params.values.flatten 1038 end 1039 1040 catch(:pass) do 1041 conditions.each { |c| throw :pass if c.bind(self).call == false } 1042 block ? block[self, values] : yield(self, values) 1043 end 1044 rescue 1045 @env['sinatra.error.params'] = @params 1046 raise 1047 ensure 1048 params ||= {} 1049 params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params'] 1050 end
Run routes defined on the class and all superclasses.
# File lib/sinatra/base.rb 989 def route!(base = settings, pass_block = nil) 990 if routes = base.routes[@request.request_method] 991 routes.each do |pattern, conditions, block| 992 returned_pass_block = process_route(pattern, conditions) do |*args| 993 env['sinatra.route'] = "#{@request.request_method} #{pattern}" 994 route_eval { block[*args] } 995 end 996 997 # don't wipe out pass_block in superclass 998 pass_block = returned_pass_block if returned_pass_block 999 end 1000 end 1001 1002 # Run routes defined in superclass. 1003 if base.superclass.respond_to?(:routes) 1004 return route!(base.superclass, pass_block) 1005 end 1006 1007 route_eval(&pass_block) if pass_block 1008 route_missing 1009 end
Run a route block and throw :halt with the result.
# File lib/sinatra/base.rb 1012 def route_eval 1013 throw :halt, yield 1014 end
No matching route was found or all routes passed. The default implementation is to forward the request downstream when running as middleware (@app is non-nil); when no downstream app is set, raise a NotFound
exception. Subclasses can override this method to perform custom route miss logic.
# File lib/sinatra/base.rb 1057 def route_missing 1058 if @app 1059 forward 1060 else 1061 raise NotFound, "#{request.request_method} #{request.path_info}" 1062 end 1063 end
Attempt to serve static files from public directory. Throws :halt when a matching file is found, returns nil otherwise.
# File lib/sinatra/base.rb 1067 def static!(options = {}) 1068 return if (public_dir = settings.public_folder).nil? 1069 path = File.expand_path("#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" ) 1070 return unless path.start_with?(File.expand_path(public_dir) + '/') 1071 return unless File.file?(path) 1072 1073 env['sinatra.static_file'] = path 1074 cache_control(*settings.static_cache_control) if settings.static_cache_control? 1075 send_file path, options.merge(:disposition => nil) 1076 end