class Sinatra::Helpers::Stream::Base
Constants
- URI_INSTANCE
Attributes
Public Class Methods
Sinatra::Helpers::Stream::Templates::new
# File lib/sinatra/base.rb 899 def initialize(app = nil) 900 super() 901 @app = app 902 @template_cache = Tilt::Cache.new 903 yield self if block_given? 904 end
Access settings defined with Base.set
.
# File lib/sinatra/base.rb 934 def self.settings 935 self 936 end
Private Class Methods
add a filter
# File lib/sinatra/base.rb 1361 def add_filter(type, path = /.*/, **options, &block) 1362 filters[type] << compile!(type, path, block, **options) 1363 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 1356 def after(path = /.*/, **options, &block) 1357 add_filter(:after, path, **options, &block) 1358 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 1349 def before(path = /.*/, **options, &block) 1350 add_filter(:before, path, **options, &block) 1351 end
Creates a Rack::Builder
instance with all the middleware set up and the given app
as end point.
# File lib/sinatra/base.rb 1495 def build(app) 1496 builder = Rack::Builder.new 1497 setup_default_middleware builder 1498 setup_middleware builder 1499 builder.run app 1500 builder 1501 end
# File lib/sinatra/base.rb 1503 def call(env) 1504 synchronize { prototype.call(env) } 1505 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 1509 def caller_files 1510 cleaned_caller(1).flatten 1511 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 1515 def caller_locations 1516 cleaned_caller 2 1517 end
Like Kernel#caller but excluding certain magic entries
# File lib/sinatra/base.rb 1741 def cleaned_caller(keep = 3) 1742 caller(1). 1743 map! { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }. 1744 reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } } 1745 end
# File lib/sinatra/base.rb 1642 def compile(path, route_mustermann_opts = {}) 1643 Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts)) 1644 end
# File lib/sinatra/base.rb 1623 def compile!(verb, path, block, **options) 1624 # Because of self.options.host 1625 host_name(options.delete(:host)) if options.key?(:host) 1626 # Pass Mustermann opts to compile() 1627 route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze 1628 1629 options.each_pair { |option, args| send(option, *args) } 1630 1631 pattern = compile(path, route_mustermann_opts) 1632 method_name = "#{verb} #{path}" 1633 unbound_method = generate_method(method_name, &block) 1634 conditions, @conditions = @conditions, [] 1635 wrapper = block.arity != 0 ? 1636 proc { |a, p| unbound_method.bind(a).call(*p) } : 1637 proc { |a, p| unbound_method.bind(a).call } 1638 1639 [ pattern, conditions, wrapper ] 1640 end
Add a route condition. The route is considered non-matching when the block returns false.
# File lib/sinatra/base.rb 1367 def condition(name = "#{caller.first[/`.*'/]} condition", &block) 1368 @conditions << generate_method(name, &block) 1369 end
Set configuration options for Sinatra
and/or the app. Allows scoping of settings for certain environments.
# File lib/sinatra/base.rb 1427 def configure(*envs) 1428 yield self if envs.empty? || envs.include?(environment.to_sym) 1429 end
Dynamically defines a method on settings.
# File lib/sinatra/base.rb 1561 def define_singleton(name, content = Proc.new) 1562 singleton_class.class_eval do 1563 undef_method(name) if method_defined? name 1564 String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content) 1565 end 1566 end
# File lib/sinatra/base.rb 1396 def delete(path, opts = {}, &bk) route 'DELETE', path, opts, &bk end
# File lib/sinatra/base.rb 1709 def detect_rack_handler 1710 servers = Array(server) 1711 servers.each do |server_name| 1712 begin 1713 return Rack::Handler.get(server_name.to_s) 1714 rescue LoadError, NameError 1715 end 1716 end 1717 fail "Server handler (#{servers.join(',')}) not found." 1718 end
# File lib/sinatra/base.rb 1421 def development?; environment == :development end
Same as calling `set :option, false` for each of the given options.
# File lib/sinatra/base.rb 1265 def disable(*opts) 1266 opts.each { |key| set(key, false) } 1267 end
Same as calling `set :option, true` for each of the given options.
# File lib/sinatra/base.rb 1260 def enable(*opts) 1261 opts.each { |key| set(key, true) } 1262 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 1272 def error(*codes, &block) 1273 args = compile! "ERROR", /.*/, block 1274 codes = codes.flat_map(&method(:Array)) 1275 codes << Exception if codes.empty? 1276 codes << Sinatra::NotFound if codes.include?(404) 1277 codes.each { |c| (@errors[c] ||= []) << args } 1278 end
Extension modules registered on this class and all superclasses.
# File lib/sinatra/base.rb 1205 def extensions 1206 if superclass.respond_to?(:extensions) 1207 (@extensions + superclass.extensions).uniq 1208 else 1209 @extensions 1210 end 1211 end
Force data to specified encoding. It defaults to settings.default_encoding which is UTF-8 by default
# File lib/sinatra/base.rb 1750 def self.force_encoding(data, encoding = default_encoding) 1751 return if data == settings || data.is_a?(Tempfile) 1752 if data.respond_to? :force_encoding 1753 data.force_encoding(encoding).encode! 1754 elsif data.respond_to? :each_value 1755 data.each_value { |v| force_encoding(v, encoding) } 1756 elsif data.respond_to? :each 1757 data.each { |v| force_encoding(v, encoding) } 1758 end 1759 data 1760 end
# File lib/sinatra/base.rb 1616 def generate_method(method_name, &block) 1617 define_method(method_name, &block) 1618 method = instance_method method_name 1619 remove_method method_name 1620 method 1621 end
Defining a `GET` handler also automatically defines a `HEAD` handler.
# File lib/sinatra/base.rb 1386 def get(path, opts = {}, &block) 1387 conditions = @conditions.dup 1388 route('GET', path, opts, &block) 1389 1390 @conditions = conditions 1391 route('HEAD', path, opts, &block) 1392 end
# File lib/sinatra/base.rb 1397 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 1405 def helpers(*extensions, &block) 1406 class_eval(&block) if block_given? 1407 include(*extensions) if extensions.any? 1408 end
Condition for matching host name. Parameter might be String or Regexp.
# File lib/sinatra/base.rb 1569 def host_name(pattern) 1570 condition { pattern === request.host } 1571 end
# File lib/sinatra/base.rb 1720 def inherited(subclass) 1721 subclass.reset! 1722 subclass.set :app_file, caller_files.first unless subclass.app_file? 1723 super 1724 end
Load embedded templates from the file; uses the caller's __FILE__ when no file is specified.
# File lib/sinatra/base.rb 1298 def inline_templates=(file = nil) 1299 file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file 1300 1301 begin 1302 io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file) 1303 app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2) 1304 rescue Errno::ENOENT 1305 app, data = nil 1306 end 1307 1308 if data 1309 if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m 1310 encoding = $2 1311 else 1312 encoding = settings.default_encoding 1313 end 1314 lines = app.count("\n") + 1 1315 template = nil 1316 force_encoding data, encoding 1317 data.each_line do |line| 1318 lines += 1 1319 if line =~ /^@@\s*(.*\S)\s*$/ 1320 template = force_encoding(String.new, encoding) 1321 templates[$1.to_sym] = [template, file, lines] 1322 elsif template 1323 template << line 1324 end 1325 end 1326 end 1327 end
# File lib/sinatra/base.rb 1612 def invoke_hook(name, *args) 1613 extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } 1614 end
Define the layout template. The block must return the template source.
# File lib/sinatra/base.rb 1292 def layout(name = :layout, &block) 1293 template name, &block 1294 end
# File lib/sinatra/base.rb 1400 def link(path, opts = {}, &bk) route 'LINK', path, opts, &bk end
Middleware used in this class and all superclasses.
# File lib/sinatra/base.rb 1214 def middleware 1215 if superclass.respond_to?(:middleware) 1216 superclass.middleware + @middleware 1217 else 1218 @middleware 1219 end 1220 end
Lookup or register a mime type in Rack's mime registry.
# File lib/sinatra/base.rb 1330 def mime_type(type, value = nil) 1331 return type if type.nil? 1332 return type.to_s if type.to_s.include?('/') 1333 type = ".#{type}" unless type.to_s[0] == ?. 1334 return Rack::Mime.mime_type(type, nil) unless value 1335 Rack::Mime::MIME_TYPES[type] = value 1336 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 1341 def mime_types(type) 1342 type = mime_type type 1343 type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type] 1344 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 1488 def new(*args, &bk) 1489 instance = new!(*args, &bk) 1490 Wrapper.new(build(instance).to_app, instance) 1491 end
Sugar for `error(404) { … }`
# File lib/sinatra/base.rb 1281 def not_found(&block) 1282 error(404, &block) 1283 end
# File lib/sinatra/base.rb 1398 def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end
# File lib/sinatra/base.rb 1399 def patch(path, opts = {}, &bk) route 'PATCH', path, opts, &bk end
# File lib/sinatra/base.rb 1395 def post(path, opts = {}, &bk) route 'POST', path, opts, &bk end
# File lib/sinatra/base.rb 1422 def production?; environment == :production end
The prototype instance used to process requests.
# File lib/sinatra/base.rb 1478 def prototype 1479 @prototype ||= new 1480 end
Condition for matching mimetypes. Accepts file extensions.
# File lib/sinatra/base.rb 1588 def provides(*types) 1589 types.map! { |t| mime_types(t) } 1590 types.flatten! 1591 condition do 1592 if type = response['Content-Type'] 1593 types.include? type or types.include? type[/^[^;]+/] 1594 elsif type = request.preferred_type(types) 1595 params = (type.respond_to?(:params) ? type.params : {}) 1596 content_type(type, params) 1597 true 1598 else 1599 false 1600 end 1601 end 1602 end
# File lib/sinatra/base.rb 1371 def public=(value) 1372 warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead" 1373 set(:public_folder, value) 1374 end
# File lib/sinatra/base.rb 1380 def public_dir 1381 public_folder 1382 end
# File lib/sinatra/base.rb 1376 def public_dir=(value) 1377 self.public_folder = value 1378 end
# File lib/sinatra/base.rb 1394 def put(path, opts = {}, &bk) route 'PUT', path, opts, &bk end
Stop the self-hosted server if running.
# File lib/sinatra/base.rb 1438 def quit! 1439 return unless running? 1440 # Use Thin's hard #stop! if available, otherwise just #stop. 1441 running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop 1442 $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless suppress_messages? 1443 set :running_server, nil 1444 set :handler_name, nil 1445 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 1412 def register(*extensions, &block) 1413 extensions << Module.new(&block) if block_given? 1414 @extensions += extensions 1415 extensions.each do |extension| 1416 extend extension 1417 extension.registered(self) if extension.respond_to?(:registered) 1418 end 1419 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 1188 def reset! 1189 @conditions = [] 1190 @routes = {} 1191 @filters = {:before => [], :after => []} 1192 @errors = {} 1193 @middleware = [] 1194 @prototype = nil 1195 @extensions = [] 1196 1197 if superclass.respond_to?(:templates) 1198 @templates = Hash.new { |hash, key| superclass.templates[key] } 1199 else 1200 @templates = {} 1201 end 1202 end
# File lib/sinatra/base.rb 1604 def route(verb, path, options = {}, &block) 1605 enable :empty_path_info if path == "" and empty_path_info.nil? 1606 signature = compile!(verb, path, block, **options) 1607 (@routes[verb] ||= []) << signature 1608 invoke_hook(:route_added, verb, path, block) 1609 signature 1610 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 1452 def run!(options = {}, &block) 1453 return if running? 1454 set options 1455 handler = detect_rack_handler 1456 handler_name = handler.name.gsub(/.*::/, '') 1457 server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {} 1458 server_settings.merge!(:Port => port, :Host => bind) 1459 1460 begin 1461 start_server(handler, server_settings, handler_name, &block) 1462 rescue Errno::EADDRINUSE 1463 $stderr.puts "== Someone is already performing on port #{port}!" 1464 raise 1465 ensure 1466 quit! 1467 end 1468 end
Check whether the self-hosted server is running or not.
# File lib/sinatra/base.rb 1473 def running? 1474 running_server? 1475 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 1224 def set(option, value = (not_set = true), ignore_setter = false, &block) 1225 raise ArgumentError if block and !not_set 1226 value, not_set = block, false if block 1227 1228 if not_set 1229 raise ArgumentError unless option.respond_to?(:each) 1230 option.each { |k,v| set(k, v) } 1231 return self 1232 end 1233 1234 if respond_to?("#{option}=") and not ignore_setter 1235 return __send__("#{option}=", value) 1236 end 1237 1238 setter = proc { |val| set option, val, true } 1239 getter = proc { value } 1240 1241 case value 1242 when Proc 1243 getter = value 1244 when Symbol, Integer, FalseClass, TrueClass, NilClass 1245 getter = value.inspect 1246 when Hash 1247 setter = proc do |val| 1248 val = value.merge val if Hash === val 1249 set option, val, true 1250 end 1251 end 1252 1253 define_singleton("#{option}=", setter) 1254 define_singleton(option, getter) 1255 define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?" 1256 self 1257 end
# File lib/sinatra/base.rb 1673 def setup_common_logger(builder) 1674 builder.use Sinatra::CommonLogger 1675 end
# File lib/sinatra/base.rb 1677 def setup_custom_logger(builder) 1678 if logging.respond_to? :to_int 1679 builder.use Rack::Logger, logging 1680 else 1681 builder.use Rack::Logger 1682 end 1683 end
# File lib/sinatra/base.rb 1646 def setup_default_middleware(builder) 1647 builder.use ExtendedRack 1648 builder.use ShowExceptions if show_exceptions? 1649 builder.use Rack::MethodOverride if method_override? 1650 builder.use Rack::Head 1651 setup_logging builder 1652 setup_sessions builder 1653 setup_protection builder 1654 end
# File lib/sinatra/base.rb 1660 def setup_logging(builder) 1661 if logging? 1662 setup_common_logger(builder) 1663 setup_custom_logger(builder) 1664 elsif logging == false 1665 setup_null_logger(builder) 1666 end 1667 end
# File lib/sinatra/base.rb 1656 def setup_middleware(builder) 1657 middleware.each { |c,a,b| builder.use(c, *a, &b) } 1658 end
# File lib/sinatra/base.rb 1669 def setup_null_logger(builder) 1670 builder.use Rack::NullLogger 1671 end
# File lib/sinatra/base.rb 1685 def setup_protection(builder) 1686 return unless protection? 1687 options = Hash === protection ? protection.dup : {} 1688 options = { 1689 img_src: "'self' data:", 1690 font_src: "'self'" 1691 }.merge options 1692 1693 protect_session = options.fetch(:session) { sessions? } 1694 options[:without_session] = !protect_session 1695 1696 options[:reaction] ||= :drop_session 1697 1698 builder.use Rack::Protection, options 1699 end
# File lib/sinatra/base.rb 1701 def setup_sessions(builder) 1702 return unless sessions? 1703 options = {} 1704 options[:secret] = session_secret if session_secret? 1705 options.merge! sessions.to_hash if sessions.respond_to? :to_hash 1706 builder.use session_store, options 1707 end
# File lib/sinatra/base.rb 1545 def setup_traps 1546 if traps? 1547 at_exit { quit! } 1548 1549 [:INT, :TERM].each do |signal| 1550 old_handler = trap(signal) do 1551 quit! 1552 old_handler.call if old_handler.respond_to?(:call) 1553 end 1554 end 1555 1556 set :traps, false 1557 end 1558 end
Starts the server by running the Rack
Handler.
# File lib/sinatra/base.rb 1522 def start_server(handler, server_settings, handler_name) 1523 # Ensure we initialize middleware before startup, to match standard Rack 1524 # behavior, by ensuring an instance exists: 1525 prototype 1526 # Run the instance we created: 1527 handler.run(self, server_settings) do |server| 1528 unless suppress_messages? 1529 $stderr.puts "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}" 1530 end 1531 1532 setup_traps 1533 set :running_server, server 1534 set :handler_name, handler_name 1535 server.threaded = settings.threaded if server.respond_to? :threaded= 1536 1537 yield server if block_given? 1538 end 1539 end
# File lib/sinatra/base.rb 1541 def suppress_messages? 1542 handler_name =~ /cgi/i || quiet 1543 end
# File lib/sinatra/base.rb 1727 def synchronize(&block) 1728 if lock? 1729 @@mutex.synchronize(&block) 1730 else 1731 yield 1732 end 1733 end
Define a named template. The block must return the template source.
# File lib/sinatra/base.rb 1286 def template(name, &block) 1287 filename, line = caller_locations.first 1288 templates[name] = [block, filename, line.to_i] 1289 end
# File lib/sinatra/base.rb 1423 def test?; environment == :test end
# File lib/sinatra/base.rb 1401 def unlink(path, opts = {}, &bk) route 'UNLINK', path, opts, &bk end
Use the specified Rack
middleware
# File lib/sinatra/base.rb 1432 def use(middleware, *args, &block) 1433 @prototype = nil 1434 @middleware << [middleware, args, block] 1435 end
Condition for matching user agent. Parameter should be Regexp. Will set params.
# File lib/sinatra/base.rb 1575 def user_agent(pattern) 1576 condition do 1577 if request.user_agent.to_s =~ pattern 1578 @params[:agent] = $~[1..-1] 1579 true 1580 else 1581 false 1582 end 1583 end 1584 end
used for deprecation warnings
# File lib/sinatra/base.rb 1736 def warn(message) 1737 super message + "\n\tfrom #{cleaned_caller.first.join(':')}" 1738 end
Public Instance Methods
Rack
call interface.
# File lib/sinatra/base.rb 907 def call(env) 908 dup.call!(env) 909 end
Forward the request to the downstream app – middleware only.
# File lib/sinatra/base.rb 964 def forward 965 fail "downstream app not set" unless @app.respond_to? :call 966 status, headers, body = @app.call env 967 @response.status = status 968 @response.body = body 969 @response.headers.merge! headers 970 nil 971 end
Exit the current block, halts any further processing of the request, and returns the specified response.
# File lib/sinatra/base.rb 951 def halt(*response) 952 response = response.first if response.length == 1 953 throw :halt, response 954 end
# File lib/sinatra/base.rb 943 def options 944 warn "Sinatra::Base#options is deprecated and will be removed, " \ 945 "use #settings instead." 946 settings 947 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 959 def pass(&block) 960 throw :pass, block 961 end
Access settings defined with Base.set
.
# File lib/sinatra/base.rb 939 def settings 940 self.class.settings 941 end
Private Instance Methods
Dispatch a request with error handling.
# File lib/sinatra/base.rb 1088 def dispatch! 1089 # Avoid passing frozen string in force_encoding 1090 @params.merge!(@request.params).each do |key, val| 1091 next unless val.respond_to?(:force_encoding) 1092 val = val.dup if val.frozen? 1093 @params[key] = force_encoding(val) 1094 end 1095 1096 invoke do 1097 static! if settings.static? && (request.get? || request.head?) 1098 filter! :before 1099 route! 1100 end 1101 rescue ::Exception => boom 1102 invoke { handle_exception!(boom) } 1103 ensure 1104 begin 1105 filter! :after unless env['sinatra.static_file'] 1106 rescue ::Exception => boom 1107 invoke { handle_exception!(boom) } unless @env['sinatra.error'] 1108 end 1109 end
# File lib/sinatra/base.rb 1161 def dump_errors!(boom) 1162 msg = ["#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - #{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t") 1163 @env['rack.errors'].puts(msg) 1164 end
Find an custom error block for the key(s) specified.
# File lib/sinatra/base.rb 1146 def error_block!(key, *block_params) 1147 base = settings 1148 while base.respond_to?(:errors) 1149 next base = base.superclass unless args_array = base.errors[key] 1150 args_array.reverse_each do |args| 1151 first = args == args_array.first 1152 args += [block_params] 1153 resp = process_route(*args) 1154 return resp unless resp.nil? && !first 1155 end 1156 end 1157 return false unless key.respond_to? :superclass and key.superclass < Exception 1158 error_block!(key.superclass, *block_params) 1159 end
Run filters defined on the class and all superclasses.
# File lib/sinatra/base.rb 976 def filter!(type, base = settings) 977 filter! type, base.superclass if base.superclass.respond_to?(:filters) 978 base.filters[type].each { |args| process_route(*args) } 979 end
# File lib/sinatra/base.rb 1762 def force_encoding(*args) settings.force_encoding(*args) end
Error handling during requests.
# File lib/sinatra/base.rb 1112 def handle_exception!(boom) 1113 if error_params = @env['sinatra.error.params'] 1114 @params = @params.merge(error_params) 1115 end 1116 @env['sinatra.error'] = boom 1117 1118 if boom.respond_to? :http_status 1119 status(boom.http_status) 1120 elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599 1121 status(boom.code) 1122 else 1123 status(500) 1124 end 1125 1126 status(500) unless status.between? 400, 599 1127 1128 boom_message = boom.message if boom.message && boom.message != boom.class.name 1129 if server_error? 1130 dump_errors! boom if settings.dump_errors? 1131 raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler 1132 elsif not_found? 1133 headers['X-Cascade'] = 'pass' if settings.x_cascade? 1134 body boom_message || '<h1>Not Found</h1>' 1135 elsif bad_request? 1136 body boom_message || '<h1>Bad Request</h1>' 1137 end 1138 1139 res = error_block!(boom.class, boom) || error_block!(status, boom) 1140 return res if res or not server_error? 1141 raise boom if settings.raise_errors? or settings.show_exceptions? 1142 error_block! Exception, boom 1143 end
Run the block with 'throw :halt' support and apply result to the response.
# File lib/sinatra/base.rb 1072 def invoke 1073 res = catch(:halt) { yield } 1074 1075 res = [res] if Integer === res or String === res 1076 if Array === res and Integer === res.first 1077 res = res.dup 1078 status(res.shift) 1079 body(res.pop) 1080 headers(*res) 1081 elsif res.respond_to? :each 1082 body res 1083 end 1084 nil # avoid double setting the same response tuple twice 1085 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 1014 def process_route(pattern, conditions, block = nil, values = []) 1015 route = @request.path_info 1016 route = '/' if route.empty? and not settings.empty_path_info? 1017 route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/') 1018 return unless params = pattern.params(route) 1019 1020 params.delete("ignore") # TODO: better params handling, maybe turn it into "smart" object or detect changes 1021 force_encoding(params) 1022 @params = @params.merge(params) if params.any? 1023 1024 regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? {|subpattern| subpattern.is_a?(Mustermann::Regular)} ) 1025 if regexp_exists 1026 captures = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c } 1027 values += captures 1028 @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty? 1029 else 1030 values += params.values.flatten 1031 end 1032 1033 catch(:pass) do 1034 conditions.each { |c| throw :pass if c.bind(self).call == false } 1035 block ? block[self, values] : yield(self, values) 1036 end 1037 rescue 1038 @env['sinatra.error.params'] = @params 1039 raise 1040 ensure 1041 params ||= {} 1042 params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params'] 1043 end
Run routes defined on the class and all superclasses.
# File lib/sinatra/base.rb 982 def route!(base = settings, pass_block = nil) 983 if routes = base.routes[@request.request_method] 984 routes.each do |pattern, conditions, block| 985 returned_pass_block = process_route(pattern, conditions) do |*args| 986 env['sinatra.route'] = "#{@request.request_method} #{pattern}" 987 route_eval { block[*args] } 988 end 989 990 # don't wipe out pass_block in superclass 991 pass_block = returned_pass_block if returned_pass_block 992 end 993 end 994 995 # Run routes defined in superclass. 996 if base.superclass.respond_to?(:routes) 997 return route!(base.superclass, pass_block) 998 end 999 1000 route_eval(&pass_block) if pass_block 1001 route_missing 1002 end
Run a route block and throw :halt with the result.
# File lib/sinatra/base.rb 1005 def route_eval 1006 throw :halt, yield 1007 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 1050 def route_missing 1051 if @app 1052 forward 1053 else 1054 raise NotFound, "#{request.request_method} #{request.path_info}" 1055 end 1056 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 1060 def static!(options = {}) 1061 return if (public_dir = settings.public_folder).nil? 1062 path = File.expand_path("#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" ) 1063 return unless path.start_with?(File.expand_path(public_dir) + '/') 1064 return unless File.file?(path) 1065 1066 env['sinatra.static_file'] = path 1067 cache_control(*settings.static_cache_control) if settings.static_cache_control? 1068 send_file path, options.merge(:disposition => nil) 1069 end