class Sinatra::Helpers::Stream::Base
Constants
- URI_INSTANCE
Attributes
Public Class Methods
Source
# File lib/sinatra/base.rb 1500 def add_filter(type, path = /.*/, **options, &block) 1501 filters[type] << compile!(type, path, block, **options) 1502 end
add a filter
Source
# File lib/sinatra/base.rb 1495 def after(path = /.*/, **options, &block) 1496 add_filter(:after, path, **options, &block) 1497 end
Define an after filter; runs after all requests within the same context as route handlers and may access/modify the request and response.
Source
# File lib/sinatra/base.rb 1488 def before(path = /.*/, **options, &block) 1489 add_filter(:before, path, **options, &block) 1490 end
Define a before filter; runs before all requests within the same context as route handlers and may access/modify the request and response.
Source
# File lib/sinatra/base.rb 1672 def build(app) 1673 builder = Rack::Builder.new 1674 setup_default_middleware builder 1675 setup_middleware builder 1676 builder.run app 1677 builder 1678 end
Creates a Rack::Builder instance with all the middleware set up and the given app as end point.
Source
# File lib/sinatra/base.rb 1680 def call(env) 1681 synchronize { prototype.call(env) } 1682 end
Source
# File lib/sinatra/base.rb 1686 def caller_files 1687 cleaned_caller(1).flatten 1688 end
Like Kernel#caller but excluding certain magic entries and without line / method information; the resulting array contains filenames only.
Source
# File lib/sinatra/base.rb 1307 def callers_to_ignore 1308 CALLERS_TO_IGNORE 1309 end
Source
# File lib/sinatra/base.rb 1514 def condition(name = "#{caller.first[/`.*'/]} condition", &block) 1515 @conditions << generate_method(name, &block) 1516 end
Add a route condition. The route is considered non-matching when the block returns false.
Source
# File lib/sinatra/base.rb 1581 def configure(*envs) 1582 yield self if envs.empty? || envs.include?(environment.to_sym) 1583 end
Set configuration options for Sinatra and/or the app. Allows scoping of settings for certain environments.
Source
# File lib/sinatra/base.rb 1545 def delete(path, opts = {}, &block) route 'DELETE', path, opts, &block end
Source
# File lib/sinatra/base.rb 1575 def development?; environment == :development end
Source
# File lib/sinatra/base.rb 1395 def disable(*opts) 1396 opts.each { |key| set(key, false) } 1397 end
Same as calling ‘set :option, false` for each of the given options.
Source
# File lib/sinatra/base.rb 1390 def enable(*opts) 1391 opts.each { |key| set(key, true) } 1392 end
Same as calling ‘set :option, true` for each of the given options.
Source
# File lib/sinatra/base.rb 1402 def error(*codes, &block) 1403 args = compile! 'ERROR', /.*/, block 1404 codes = codes.flat_map(&method(:Array)) 1405 codes << Exception if codes.empty? 1406 codes << Sinatra::NotFound if codes.include?(404) 1407 codes.each { |c| (@errors[c] ||= []) << args } 1408 end
Define a custom error handler. Optionally takes either an Exception class, or an HTTP status code to specify which errors should be handled.
Source
# File lib/sinatra/base.rb 1330 def extensions 1331 if superclass.respond_to?(:extensions) 1332 (@extensions + superclass.extensions).uniq 1333 else 1334 @extensions 1335 end 1336 end
Extension modules registered on this class and all superclasses.
Source
# File lib/sinatra/base.rb 1921 def self.force_encoding(data, encoding = default_encoding) 1922 return if data == settings || data.is_a?(Tempfile) 1923 1924 if data.respond_to? :force_encoding 1925 data.force_encoding(encoding).encode! 1926 elsif data.respond_to? :each_value 1927 data.each_value { |v| force_encoding(v, encoding) } 1928 elsif data.respond_to? :each 1929 data.each { |v| force_encoding(v, encoding) } 1930 end 1931 data 1932 end
Force data to specified encoding. It defaults to settings.default_encoding which is UTF-8 by default
Source
# File lib/sinatra/base.rb 1533 def get(path, opts = {}, &block) 1534 conditions = @conditions.dup 1535 route('GET', path, opts, &block) 1536 1537 @conditions = conditions 1538 route('HEAD', path, opts, &block) 1539 end
Defining a ‘GET` handler also automatically defines a `HEAD` handler.
Source
# File lib/sinatra/base.rb 1547 def head(path, opts = {}, &block) route 'HEAD', path, opts, &block end
Source
# File lib/sinatra/base.rb 1559 def helpers(*extensions, &block) 1560 class_eval(&block) if block_given? 1561 include(*extensions) if extensions.any? 1562 end
Makes the methods defined in the block and in the Modules given in ‘extensions` available to the handlers and templates
Source
# File lib/sinatra/base.rb 1428 def inline_templates=(file = nil) 1429 file = (caller_files.first || File.expand_path($0)) if file.nil? || file == true 1430 1431 begin 1432 io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file) 1433 app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2) 1434 rescue Errno::ENOENT 1435 app, data = nil 1436 end 1437 1438 return unless data 1439 1440 encoding = if app && app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m 1441 $2 1442 else 1443 settings.default_encoding 1444 end 1445 1446 lines = app.count("\n") + 1 1447 template = nil 1448 force_encoding data, encoding 1449 data.each_line do |line| 1450 lines += 1 1451 if line =~ /^@@\s*(.*\S)\s*$/ 1452 template = force_encoding(String.new, encoding) 1453 templates[$1.to_sym] = [template, file, lines] 1454 elsif template 1455 template << line 1456 end 1457 end 1458 end
Load embedded templates from the file; uses the caller’s __FILE__ when no file is specified.
Source
# File lib/sinatra/base.rb 1422 def layout(name = :layout, &block) 1423 template name, &block 1424 end
Define the layout template. The block must return the template source.
Source
# File lib/sinatra/base.rb 1553 def link(path, opts = {}, &block) route 'LINK', path, opts, &block end
Source
# File lib/sinatra/base.rb 1339 def middleware 1340 if superclass.respond_to?(:middleware) 1341 superclass.middleware + @middleware 1342 else 1343 @middleware 1344 end 1345 end
Middleware used in this class and all superclasses.
Source
# File lib/sinatra/base.rb 1461 def mime_type(type, value = nil) 1462 return type if type.nil? 1463 return type.to_s if type.to_s.include?('/') 1464 1465 type = ".#{type}" unless type.to_s[0] == '.' 1466 return Rack::Mime.mime_type(type, nil) unless value 1467 1468 Rack::Mime::MIME_TYPES[type] = value 1469 end
Lookup or register a mime type in Rack’s mime registry.
Source
# File lib/sinatra/base.rb 1474 def mime_types(type) 1475 type = mime_type type 1476 if type =~ %r{^application/(xml|javascript)$} 1477 [type, "text/#{$1}"] 1478 elsif type =~ %r{^text/(xml|javascript)$} 1479 [type, "application/#{$1}"] 1480 else 1481 [type] 1482 end 1483 end
provides all mime types matching type, including deprecated types:
mime_types :html # => ['text/html'] mime_types :js # => ['application/javascript', 'text/javascript']
Source
# File lib/sinatra/base.rb 983 def initialize(app = nil, **_kwargs) 984 super() 985 @app = app 986 @template_cache = TemplateCache.new 987 @pinned_response = nil # whether a before! filter pinned the content-type 988 yield self if block_given? 989 end
Sinatra::Helpers::Stream::Templates::new
Source
# File lib/sinatra/base.rb 1664 def new(*args, &block) 1665 instance = new!(*args, &block) 1666 Wrapper.new(build(instance).to_app, instance) 1667 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.
Source
# File lib/sinatra/base.rb 1411 def not_found(&block) 1412 error(404, &block) 1413 end
Sugar for ‘error(404) { … }`
Source
# File lib/sinatra/base.rb 1504 def on_start(&on_start_callback) 1505 @on_start_callback = on_start_callback 1506 end
Source
# File lib/sinatra/base.rb 1508 def on_stop(&on_stop_callback) 1509 @on_stop_callback = on_stop_callback 1510 end
Source
# File lib/sinatra/base.rb 1549 def options(path, opts = {}, &block) route 'OPTIONS', path, opts, &block end
Source
# File lib/sinatra/base.rb 1551 def patch(path, opts = {}, &block) route 'PATCH', path, opts, &block end
Source
# File lib/sinatra/base.rb 1543 def post(path, opts = {}, &block) route 'POST', path, opts, &block end
Source
# File lib/sinatra/base.rb 1576 def production?; environment == :production end
Source
# File lib/sinatra/base.rb 1654 def prototype 1655 @prototype ||= new 1656 end
The prototype instance used to process requests.
Source
# File lib/sinatra/base.rb 1518 def public=(value) 1519 warn_for_deprecation ':public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead' 1520 set(:public_folder, value) 1521 end
Source
# File lib/sinatra/base.rb 1523 def public_dir=(value) 1524 self.public_folder = value 1525 end
Source
# File lib/sinatra/base.rb 1541 def put(path, opts = {}, &block) route 'PUT', path, opts, &block end
Source
# File lib/sinatra/base.rb 1593 def quit! 1594 return unless running? 1595 1596 # Use Thin's hard #stop! if available, otherwise just #stop. 1597 running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop 1598 warn '== Sinatra has ended his set (crowd applauds)' unless suppress_messages? 1599 set :running_server, nil 1600 set :handler_name, nil 1601 1602 on_stop_callback.call unless on_stop_callback.nil? 1603 end
Stop the self-hosted server if running.
Source
# File lib/sinatra/base.rb 1566 def register(*extensions, &block) 1567 extensions << Module.new(&block) if block_given? 1568 @extensions += extensions 1569 extensions.each do |extension| 1570 extend extension 1571 extension.registered(self) if extension.respond_to?(:registered) 1572 end 1573 end
Register an extension. Alternatively take a block from which an extension will be created and registered on the fly.
Source
# File lib/sinatra/base.rb 1313 def reset! 1314 @conditions = [] 1315 @routes = {} 1316 @filters = { before: [], after: [] } 1317 @errors = {} 1318 @middleware = [] 1319 @prototype = nil 1320 @extensions = [] 1321 1322 @templates = if superclass.respond_to?(:templates) 1323 Hash.new { |_hash, key| superclass.templates[key] } 1324 else 1325 {} 1326 end 1327 end
Removes all routes, filters, middleware and extension hooks from the current class (not routes/filters/… defined by its superclass).
Source
# File lib/sinatra/base.rb 1610 def run!(options = {}, &block) 1611 unless defined?(Rackup::Handler) 1612 rackup_warning = <<~MISSING_RACKUP 1613 Sinatra could not start, the required gems weren't found! 1614 1615 Add them to your bundle with: 1616 1617 bundle add rackup puma 1618 1619 or install them with: 1620 1621 gem install rackup puma 1622 1623 MISSING_RACKUP 1624 warn rackup_warning 1625 exit 1 1626 end 1627 1628 return if running? 1629 1630 set options 1631 handler = Rackup::Handler.pick(server) 1632 handler_name = handler.name.gsub(/.*::/, '') 1633 server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {} 1634 server_settings.merge!(Port: port, Host: bind) 1635 1636 begin 1637 start_server(handler, server_settings, handler_name, &block) 1638 rescue Errno::EADDRINUSE 1639 warn "== Someone is already performing on port #{port}!" 1640 raise 1641 ensure 1642 quit! 1643 end 1644 end
Run the Sinatra app as a self-hosted server using Puma, Falcon (in that order). If given a block, will call with the constructed handler once we have taken the stage.
Source
# File lib/sinatra/base.rb 1649 def running? 1650 running_server? 1651 end
Check whether the self-hosted server is running or not.
Source
# File lib/sinatra/base.rb 1349 def set(option, value = (not_set = true), ignore_setter = false, &block) 1350 raise ArgumentError if block && !not_set 1351 1352 if block 1353 value = block 1354 not_set = false 1355 end 1356 1357 if not_set 1358 raise ArgumentError unless option.respond_to?(:each) 1359 1360 option.each { |k, v| set(k, v) } 1361 return self 1362 end 1363 1364 if respond_to?("#{option}=") && !ignore_setter 1365 return __send__("#{option}=", value) 1366 end 1367 1368 setter = proc { |val| set option, val, true } 1369 getter = proc { value } 1370 1371 case value 1372 when Proc 1373 getter = value 1374 when Symbol, Integer, FalseClass, TrueClass, NilClass 1375 getter = value.inspect 1376 when Hash 1377 setter = proc do |val| 1378 val = value.merge val if Hash === val 1379 set option, val, true 1380 end 1381 end 1382 1383 define_singleton("#{option}=", setter) 1384 define_singleton(option, getter) 1385 define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?" 1386 self 1387 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.
Source
# File lib/sinatra/base.rb 1019 def self.settings 1020 self 1021 end
Access settings defined with Base.set.
Source
# File lib/sinatra/base.rb 1416 def template(name, &block) 1417 filename, line = caller_locations.first 1418 templates[name] = [block, filename, line.to_i] 1419 end
Define a named template. The block must return the template source.
Source
# File lib/sinatra/base.rb 1555 def unlink(path, opts = {}, &block) route 'UNLINK', path, opts, &block end
Source
# File lib/sinatra/base.rb 1586 def use(middleware, *args, &block) 1587 @prototype = nil 1588 @middleware << [middleware, args, block] 1589 end
Use the specified Rack middleware
Private Class Methods
Source
# File lib/sinatra/base.rb 1912 def cleaned_caller(keep = 3) 1913 caller(1) 1914 .map! { |line| line.split(/:(?=\d|in )/, 3)[0, keep] } 1915 .reject { |file, *_| callers_to_ignore.any? { |pattern| file =~ pattern } } 1916 end
Like Kernel#caller but excluding certain magic entries
Source
# File lib/sinatra/base.rb 1817 def compile(path, route_mustermann_opts = {}) 1818 Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts)) 1819 end
Source
# File lib/sinatra/base.rb 1797 def compile!(verb, path, block, **options) 1798 # Because of self.options.host 1799 host_name(options.delete(:host)) if options.key?(:host) 1800 # Pass Mustermann opts to compile() 1801 route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze 1802 1803 options.each_pair { |option, args| send(option, *args) } 1804 1805 pattern = compile(path, route_mustermann_opts) 1806 method_name = "#{verb} #{path}" 1807 unbound_method = generate_method(method_name, &block) 1808 conditions = @conditions 1809 @conditions = [] 1810 wrapper = block.arity.zero? ? 1811 proc { |a, _p| unbound_method.bind(a).call } : 1812 proc { |a, p| unbound_method.bind(a).call(*p) } 1813 1814 [pattern, conditions, wrapper] 1815 end
Source
# File lib/sinatra/base.rb 1732 def define_singleton(name, content = Proc.new) 1733 singleton_class.class_eval do 1734 undef_method(name) if method_defined? name 1735 String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content) 1736 end 1737 end
Dynamically defines a method on settings.
Source
# File lib/sinatra/base.rb 1790 def generate_method(method_name, &block) 1791 define_method(method_name, &block) 1792 method = instance_method method_name 1793 remove_method method_name 1794 method 1795 end
Source
# File lib/sinatra/base.rb 1740 def host_name(pattern) 1741 condition { pattern === request.host } 1742 end
Condition for matching host name. Parameter might be String or Regexp.
Source
# File lib/sinatra/base.rb 1891 def inherited(subclass) 1892 subclass.reset! 1893 subclass.set :app_file, caller_files.first unless subclass.app_file? 1894 super 1895 end
Source
# File lib/sinatra/base.rb 1786 def invoke_hook(name, *args) 1787 extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } 1788 end
Source
# File lib/sinatra/base.rb 1759 def provides(*types) 1760 types.map! { |t| mime_types(t) } 1761 types.flatten! 1762 condition do 1763 response_content_type = response['content-type'] 1764 preferred_type = request.preferred_type(types) 1765 1766 if response_content_type 1767 types.include?(response_content_type) || types.include?(response_content_type[/^[^;]+/]) 1768 elsif preferred_type 1769 params = (preferred_type.respond_to?(:params) ? preferred_type.params : {}) 1770 content_type(preferred_type, params) 1771 true 1772 else 1773 false 1774 end 1775 end 1776 end
Condition for matching mimetypes. Accepts file extensions.
Source
# File lib/sinatra/base.rb 1778 def route(verb, path, options = {}, &block) 1779 enable :empty_path_info if path == '' && empty_path_info.nil? 1780 signature = compile!(verb, path, block, **options) 1781 (@routes[verb] ||= []) << signature 1782 invoke_hook(:route_added, verb, path, block) 1783 signature 1784 end
Source
# File lib/sinatra/base.rb 1849 def setup_common_logger(builder) 1850 builder.use Sinatra::CommonLogger 1851 end
Source
# File lib/sinatra/base.rb 1853 def setup_custom_logger(builder) 1854 if logging.respond_to? :to_int 1855 builder.use Sinatra::Middleware::Logger, logging 1856 else 1857 builder.use Sinatra::Middleware::Logger 1858 end 1859 end
Source
# File lib/sinatra/base.rb 1821 def setup_default_middleware(builder) 1822 builder.use ExtendedRack 1823 builder.use ShowExceptions if show_exceptions? 1824 builder.use Rack::MethodOverride if method_override? 1825 builder.use Rack::Head 1826 setup_logging builder 1827 setup_sessions builder 1828 setup_protection builder 1829 setup_host_authorization builder 1830 end
Source
# File lib/sinatra/base.rb 1836 def setup_logging(builder) 1837 if logging? 1838 setup_common_logger(builder) 1839 setup_custom_logger(builder) 1840 elsif logging == false 1841 setup_null_logger(builder) 1842 end 1843 end
Source
# File lib/sinatra/base.rb 1832 def setup_middleware(builder) 1833 middleware.each { |c, a, b| builder.use(c, *a, &b) } 1834 end
Source
# File lib/sinatra/base.rb 1845 def setup_null_logger(builder) 1846 builder.use Sinatra::Middleware::Logger, ::Logger::FATAL 1847 end
Source
# File lib/sinatra/base.rb 1861 def setup_protection(builder) 1862 return unless protection? 1863 1864 options = Hash === protection ? protection.dup : {} 1865 options = { 1866 img_src: "'self' data:", 1867 font_src: "'self'" 1868 }.merge options 1869 1870 protect_session = options.fetch(:session) { sessions? } 1871 options[:without_session] = !protect_session 1872 1873 options[:reaction] ||= :drop_session 1874 1875 builder.use Rack::Protection, options 1876 end
Source
# File lib/sinatra/base.rb 1882 def setup_sessions(builder) 1883 return unless sessions? 1884 1885 options = {} 1886 options[:secret] = session_secret if session_secret? 1887 options.merge! sessions.to_hash if sessions.respond_to? :to_hash 1888 builder.use session_store, options 1889 end
Source
# File lib/sinatra/base.rb 1716 def setup_traps 1717 return unless traps? 1718 1719 at_exit { quit! } 1720 1721 %i[INT TERM].each do |signal| 1722 old_handler = trap(signal) do 1723 quit! 1724 old_handler.call if old_handler.respond_to?(:call) 1725 end 1726 end 1727 1728 set :traps, false 1729 end
Source
# File lib/sinatra/base.rb 1693 def start_server(handler, server_settings, handler_name) 1694 # Ensure we initialize middleware before startup, to match standard Rack 1695 # behavior, by ensuring an instance exists: 1696 prototype 1697 # Run the instance we created: 1698 handler.run(self, **server_settings) do |server| 1699 unless suppress_messages? 1700 warn "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}" 1701 end 1702 1703 setup_traps 1704 set :running_server, server 1705 set :handler_name, handler_name 1706 server.threaded = settings.threaded if server.respond_to? :threaded= 1707 on_start_callback.call unless on_start_callback.nil? 1708 yield server if block_given? 1709 end 1710 end
Starts the server by running the Rack Handler.
Source
# File lib/sinatra/base.rb 1712 def suppress_messages? 1713 handler_name =~ /cgi/i || quiet 1714 end
Source
# File lib/sinatra/base.rb 1898 def synchronize(&block) 1899 if lock? 1900 @@mutex.synchronize(&block) 1901 else 1902 yield 1903 end 1904 end
Source
# File lib/sinatra/base.rb 1746 def user_agent(pattern) 1747 condition do 1748 if request.user_agent.to_s =~ pattern 1749 @params[:agent] = $~[1..-1] 1750 true 1751 else 1752 false 1753 end 1754 end 1755 end
Condition for matching user agent. Parameter should be Regexp. Will set params.
Source
# File lib/sinatra/base.rb 1907 def warn_for_deprecation(message) 1908 warn message + "\n\tfrom #{cleaned_caller.first.join(':')}" 1909 end
used for deprecation warnings
Public Instance Methods
Source
# File lib/sinatra/base.rb 1043 def forward 1044 raise 'downstream app not set' unless @app.respond_to? :call 1045 1046 status, headers, body = @app.call env 1047 @response.status = status 1048 @response.body = body 1049 @response.headers.merge! headers 1050 nil 1051 end
Forward the request to the downstream app – middleware only.
Source
# File lib/sinatra/base.rb 1030 def halt(*response) 1031 response = response.first if response.length == 1 1032 throw :halt, response 1033 end
Exit the current block, halts any further processing of the request, and returns the specified response.
Source
# File lib/sinatra/base.rb 1038 def pass(&block) 1039 throw :pass, block 1040 end
Pass control to the next matching route. If there are no more matching routes, Sinatra will return a 404 response.
Source
# File lib/sinatra/base.rb 1024 def settings 1025 self.class.settings 1026 end
Access settings defined with Base.set.
Private Instance Methods
Source
# File lib/sinatra/base.rb 1183 def dispatch! 1184 # Avoid passing frozen string in force_encoding 1185 @params.merge!(@request.params).each do |key, val| 1186 next unless val.respond_to?(:force_encoding) 1187 1188 val = val.dup if val.frozen? 1189 @params[key] = force_encoding(val) 1190 end 1191 1192 invoke do 1193 static! if settings.static? && (request.get? || request.head?) 1194 filter! :before do 1195 @pinned_response = !response['content-type'].nil? 1196 end 1197 route! 1198 end 1199 rescue ::Exception => e 1200 invoke { handle_exception!(e) } 1201 ensure 1202 begin 1203 filter! :after unless env['sinatra.static_file'] 1204 rescue ::Exception => e 1205 invoke { handle_exception!(e) } unless @env['sinatra.error'] 1206 end 1207 end
Dispatch a request with error handling.
Source
# File lib/sinatra/base.rb 1275 def dump_errors!(boom) 1276 if boom.respond_to?(:detailed_message) 1277 msg = boom.detailed_message(highlight: false) 1278 if msg =~ /\A(.*?)(?: \(#{ Regexp.quote(boom.class.to_s) }\))?\n/ 1279 msg = $1 1280 additional_msg = $'.lines(chomp: true) 1281 else 1282 additional_msg = [] 1283 end 1284 else 1285 msg = boom.message 1286 additional_msg = [] 1287 end 1288 msg = ["#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} - #{boom.class} - #{msg}:", *additional_msg, *boom.backtrace].join("\n\t") 1289 @env['rack.errors'].puts(msg) 1290 end
Source
# File lib/sinatra/base.rb 1256 def error_block!(key, *block_params) 1257 base = settings 1258 while base.respond_to?(:errors) 1259 args_array = base.errors[key] 1260 1261 next base = base.superclass unless args_array 1262 1263 args_array.reverse_each do |args| 1264 first = args == args_array.first 1265 args += [block_params] 1266 resp = process_route(*args) 1267 return resp unless resp.nil? && !first 1268 end 1269 end 1270 return false unless key.respond_to?(:superclass) && (key.superclass < Exception) 1271 1272 error_block!(key.superclass, *block_params) 1273 end
Find an custom error block for the key(s) specified.
Source
# File lib/sinatra/base.rb 1057 def filter!(type, base = settings, &block) 1058 filter!(type, base.superclass, &block) if base.superclass.respond_to?(:filters) 1059 base.filters[type].each do |args| 1060 result = process_route(*args) 1061 block.call(result) if block_given? 1062 end 1063 end
Run filters defined on the class and all superclasses. Accepts an optional block to call after each filter is applied.
Source
# File lib/sinatra/base.rb 1934 def force_encoding(*args) 1935 settings.force_encoding(*args) 1936 end
Source
# File lib/sinatra/base.rb 1210 def handle_exception!(boom) 1211 error_params = @env['sinatra.error.params'] 1212 1213 @params = @params.merge(error_params) if error_params 1214 1215 @env['sinatra.error'] = boom 1216 1217 http_status = if boom.is_a? Sinatra::Error 1218 if boom.respond_to? :http_status 1219 boom.http_status 1220 elsif settings.use_code? && boom.respond_to?(:code) 1221 boom.code 1222 end 1223 end 1224 1225 http_status = 500 unless http_status&.between?(400, 599) 1226 status(http_status) 1227 1228 if server_error? 1229 dump_errors! boom if settings.dump_errors? 1230 raise boom if settings.show_exceptions? && (settings.show_exceptions != :after_handler) 1231 elsif not_found? 1232 headers['X-Cascade'] = 'pass' if settings.x_cascade? 1233 end 1234 1235 if (res = error_block!(boom.class, boom) || error_block!(status, boom)) 1236 return res 1237 end 1238 1239 if not_found? || bad_request? 1240 if boom.message && boom.message != boom.class.name 1241 body Rack::Utils.escape_html(boom.message) 1242 else 1243 content_type 'text/html' 1244 body "<h1>#{not_found? ? 'Not Found' : 'Bad Request'}</h1>" 1245 end 1246 end 1247 1248 return unless server_error? 1249 1250 raise boom if settings.raise_errors? || settings.show_exceptions? 1251 1252 error_block! Exception, boom 1253 end
Error handling during requests.
Source
# File lib/sinatra/base.rb 1167 def invoke(&block) 1168 res = catch(:halt, &block) 1169 1170 res = [res] if (Integer === res) || (String === res) 1171 if (Array === res) && (Integer === res.first) 1172 res = res.dup 1173 status(res.shift) 1174 body(res.pop) 1175 headers(*res) 1176 elsif res.respond_to? :each 1177 body res 1178 end 1179 nil # avoid double setting the same response tuple twice 1180 end
Run the block with ‘throw :halt’ support and apply result to the response.
Source
# File lib/sinatra/base.rb 1100 def process_route(pattern, conditions, block = nil, values = []) 1101 route = @request.path_info 1102 route = '/' if route.empty? && !settings.empty_path_info? 1103 route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/') 1104 1105 params = pattern.params(route) 1106 return unless params 1107 1108 params.delete('ignore') # TODO: better params handling, maybe turn it into "smart" object or detect changes 1109 force_encoding(params) 1110 @params = @params.merge(params) { |_k, v1, v2| v2 || v1 } if params.any? 1111 1112 regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? { |subpattern| subpattern.is_a?(Mustermann::Regular) }) 1113 if regexp_exists 1114 captures = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c } 1115 values += captures 1116 @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty? 1117 else 1118 values += params.values.flatten 1119 end 1120 1121 catch(:pass) do 1122 conditions.each { |c| throw :pass if c.bind(self).call == false } 1123 block ? block[self, values] : yield(self, values) 1124 end 1125 rescue StandardError 1126 @env['sinatra.error.params'] = @params 1127 raise 1128 ensure 1129 params ||= {} 1130 params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params'] 1131 end
If the current request matches pattern and conditions, fill params with keys and call the given block. Revert params afterwards.
Returns pass block.
Source
# File lib/sinatra/base.rb 1066 def route!(base = settings, pass_block = nil) 1067 routes = base.routes[@request.request_method] 1068 1069 routes&.each do |pattern, conditions, block| 1070 response.delete_header('content-type') unless @pinned_response 1071 1072 returned_pass_block = process_route(pattern, conditions) do |*args| 1073 env['sinatra.route'] = "#{@request.request_method} #{pattern}" 1074 route_eval { block[*args] } 1075 end 1076 1077 # don't wipe out pass_block in superclass 1078 pass_block = returned_pass_block if returned_pass_block 1079 end 1080 1081 # Run routes defined in superclass. 1082 if base.superclass.respond_to?(:routes) 1083 return route!(base.superclass, pass_block) 1084 end 1085 1086 route_eval(&pass_block) if pass_block 1087 route_missing 1088 end
Run routes defined on the class and all superclasses.
Source
# File lib/sinatra/base.rb 1091 def route_eval 1092 throw :halt, yield 1093 end
Run a route block and throw :halt with the result.
Source
# File lib/sinatra/base.rb 1138 def route_missing 1139 raise NotFound unless @app 1140 1141 forward 1142 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.
Source
# File lib/sinatra/base.rb 1147 def static!(options = {}) 1148 return if (public_dir = settings.public_folder).nil? 1149 1150 path = "#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" 1151 return unless valid_path?(path) 1152 1153 path = File.expand_path(path) 1154 return unless path.start_with?("#{File.expand_path(public_dir)}/") 1155 1156 return unless File.file?(path) 1157 1158 env['sinatra.static_file'] = path 1159 cache_control(*settings.static_cache_control) if settings.static_cache_control? 1160 1161 headers(settings.static_headers) if settings.static_headers? 1162 1163 send_file path, options.merge(disposition: nil) 1164 end
Attempt to serve static files from public directory. Throws :halt when a matching file is found, returns nil otherwise. If custom static headers are defined, use them.