class Sinatra::Helpers::Stream::Base

Base class for all Sinatra applications and middleware.

Constants

URI_INSTANCE

Attributes

errors[R]
filters[R]
routes[R]
templates[R]
app[RW]
env[RW]
params[RW]
request[RW]
response[RW]
template_cache[R]

Public Class Methods

new(app = nil) { |self| ... } click to toggle source
    # File lib/sinatra/base.rb
902 def initialize(app = nil)
903   super()
904   @app = app
905   @template_cache = Tilt::Cache.new
906   yield self if block_given?
907 end
Also aliased as: new!
settings() click to toggle source

Access settings defined with Base.set.

    # File lib/sinatra/base.rb
937 def self.settings
938   self
939 end

Private Class Methods

add_filter(type, path = /.*/, **options, &block) click to toggle source

add a filter

     # File lib/sinatra/base.rb
1364 def add_filter(type, path = /.*/, **options, &block)
1365   filters[type] << compile!(type, path, block, **options)
1366 end
after(path = /.*/, **options, &block) click to toggle source

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
1359 def after(path = /.*/, **options, &block)
1360   add_filter(:after, path, **options, &block)
1361 end
agent(pattern)
Alias for: user_agent
before(path = /.*/, **options, &block) click to toggle source

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
1352 def before(path = /.*/, **options, &block)
1353   add_filter(:before, path, **options, &block)
1354 end
build(app) click to toggle source

Creates a Rack::Builder instance with all the middleware set up and the given app as end point.

     # File lib/sinatra/base.rb
1498 def build(app)
1499   builder = Rack::Builder.new
1500   setup_default_middleware builder
1501   setup_middleware builder
1502   builder.run app
1503   builder
1504 end
call(env) click to toggle source
     # File lib/sinatra/base.rb
1506 def call(env)
1507   synchronize { prototype.call(env) }
1508 end
caller_files() click to toggle source

Like Kernel#caller but excluding certain magic entries and without line / method information; the resulting array contains filenames only.

     # File lib/sinatra/base.rb
1512 def caller_files
1513   cleaned_caller(1).flatten
1514 end
caller_locations() click to toggle source

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
1518 def caller_locations
1519   cleaned_caller 2
1520 end
cleaned_caller(keep = 3) click to toggle source

Like Kernel#caller but excluding certain magic entries

     # File lib/sinatra/base.rb
1744 def cleaned_caller(keep = 3)
1745   caller(1).
1746     map!    { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }.
1747     reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } }
1748 end
compile(path, route_mustermann_opts = {}) click to toggle source
     # File lib/sinatra/base.rb
1645 def compile(path, route_mustermann_opts = {})
1646   Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts))
1647 end
compile!(verb, path, block, **options) click to toggle source
     # File lib/sinatra/base.rb
1626 def compile!(verb, path, block, **options)
1627   # Because of self.options.host
1628   host_name(options.delete(:host)) if options.key?(:host)
1629   # Pass Mustermann opts to compile()
1630   route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze
1631 
1632   options.each_pair { |option, args| send(option, *args) }
1633 
1634   pattern                 = compile(path, route_mustermann_opts)
1635   method_name             = "#{verb} #{path}"
1636   unbound_method          = generate_method(method_name, &block)
1637   conditions, @conditions = @conditions, []
1638   wrapper                 = block.arity != 0 ?
1639     proc { |a, p| unbound_method.bind(a).call(*p) } :
1640     proc { |a, p| unbound_method.bind(a).call }
1641 
1642   [ pattern, conditions, wrapper ]
1643 end
condition(name = " click to toggle source

Add a route condition. The route is considered non-matching when the block returns false.

     # File lib/sinatra/base.rb
1370 def condition(name = "#{caller.first[/`.*'/]} condition", &block)
1371   @conditions << generate_method(name, &block)
1372 end
configure(*envs) { |self| ... } click to toggle source

Set configuration options for Sinatra and/or the app. Allows scoping of settings for certain environments.

     # File lib/sinatra/base.rb
1430 def configure(*envs)
1431   yield self if envs.empty? || envs.include?(environment.to_sym)
1432 end
define_singleton(name, content = Proc.new) click to toggle source

Dynamically defines a method on settings.

     # File lib/sinatra/base.rb
1564 def define_singleton(name, content = Proc.new)
1565   singleton_class.class_eval do
1566     undef_method(name) if method_defined? name
1567     String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content)
1568   end
1569 end
delete(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1399 def delete(path, opts = {}, &bk)  route 'DELETE',  path, opts, &bk end
detect_rack_handler() click to toggle source
     # File lib/sinatra/base.rb
1712 def detect_rack_handler
1713   servers = Array(server)
1714   servers.each do |server_name|
1715     begin
1716       return Rack::Handler.get(server_name.to_s)
1717     rescue LoadError, NameError
1718     end
1719   end
1720   fail "Server handler (#{servers.join(',')}) not found."
1721 end
development?() click to toggle source
     # File lib/sinatra/base.rb
1424 def development?; environment == :development end
disable(*opts) click to toggle source

Same as calling ‘set :option, false` for each of the given options.

     # File lib/sinatra/base.rb
1268 def disable(*opts)
1269   opts.each { |key| set(key, false) }
1270 end
enable(*opts) click to toggle source

Same as calling ‘set :option, true` for each of the given options.

     # File lib/sinatra/base.rb
1263 def enable(*opts)
1264   opts.each { |key| set(key, true) }
1265 end
error(*codes, &block) click to toggle source

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
1275 def error(*codes, &block)
1276   args  = compile! "ERROR", /.*/, block
1277   codes = codes.flat_map(&method(:Array))
1278   codes << Exception if codes.empty?
1279   codes << Sinatra::NotFound if codes.include?(404)
1280   codes.each { |c| (@errors[c] ||= []) << args }
1281 end
extensions() click to toggle source

Extension modules registered on this class and all superclasses.

     # File lib/sinatra/base.rb
1208 def extensions
1209   if superclass.respond_to?(:extensions)
1210     (@extensions + superclass.extensions).uniq
1211   else
1212     @extensions
1213   end
1214 end
force_encoding(data, encoding = default_encoding) click to toggle source

Force data to specified encoding. It defaults to settings.default_encoding which is UTF-8 by default

     # File lib/sinatra/base.rb
1753 def self.force_encoding(data, encoding = default_encoding)
1754   return if data == settings || data.is_a?(Tempfile)
1755   if data.respond_to? :force_encoding
1756     data.force_encoding(encoding).encode!
1757   elsif data.respond_to? :each_value
1758     data.each_value { |v| force_encoding(v, encoding) }
1759   elsif data.respond_to? :each
1760     data.each { |v| force_encoding(v, encoding) }
1761   end
1762   data
1763 end
generate_method(method_name, &block) click to toggle source
     # File lib/sinatra/base.rb
1619 def generate_method(method_name, &block)
1620   define_method(method_name, &block)
1621   method = instance_method method_name
1622   remove_method method_name
1623   method
1624 end
get(path, opts = {}, &block) click to toggle source

Defining a ‘GET` handler also automatically defines a `HEAD` handler.

     # File lib/sinatra/base.rb
1389 def get(path, opts = {}, &block)
1390   conditions = @conditions.dup
1391   route('GET', path, opts, &block)
1392 
1393   @conditions = conditions
1394   route('HEAD', path, opts, &block)
1395 end
head(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1400 def head(path, opts = {}, &bk)    route 'HEAD',    path, opts, &bk end
helpers(*extensions, &block) click to toggle source

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
1408 def helpers(*extensions, &block)
1409   class_eval(&block)   if block_given?
1410   include(*extensions) if extensions.any?
1411 end
host_name(pattern) click to toggle source

Condition for matching host name. Parameter might be String or Regexp.

     # File lib/sinatra/base.rb
1572 def host_name(pattern)
1573   condition { pattern === request.host }
1574 end
inherited(subclass) click to toggle source
Calls superclass method
     # File lib/sinatra/base.rb
1723 def inherited(subclass)
1724   subclass.reset!
1725   subclass.set :app_file, caller_files.first unless subclass.app_file?
1726   super
1727 end
inline_templates=(file = nil) click to toggle source

Load embedded templates from the file; uses the caller’s __FILE__ when no file is specified.

     # File lib/sinatra/base.rb
1301 def inline_templates=(file = nil)
1302   file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file
1303 
1304   begin
1305     io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file)
1306     app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2)
1307   rescue Errno::ENOENT
1308     app, data = nil
1309   end
1310 
1311   if data
1312     if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m
1313       encoding = $2
1314     else
1315       encoding = settings.default_encoding
1316     end
1317     lines = app.count("\n") + 1
1318     template = nil
1319     force_encoding data, encoding
1320     data.each_line do |line|
1321       lines += 1
1322       if line =~ /^@@\s*(.*\S)\s*$/
1323         template = force_encoding(String.new, encoding)
1324         templates[$1.to_sym] = [template, file, lines]
1325       elsif template
1326         template << line
1327       end
1328     end
1329   end
1330 end
invoke_hook(name, *args) click to toggle source
     # File lib/sinatra/base.rb
1615 def invoke_hook(name, *args)
1616   extensions.each { |e| e.send(name, *args) if e.respond_to?(name) }
1617 end
layout(name = :layout, &block) click to toggle source

Define the layout template. The block must return the template source.

     # File lib/sinatra/base.rb
1295 def layout(name = :layout, &block)
1296   template name, &block
1297 end
middleware() click to toggle source

Middleware used in this class and all superclasses.

     # File lib/sinatra/base.rb
1217 def middleware
1218   if superclass.respond_to?(:middleware)
1219     superclass.middleware + @middleware
1220   else
1221     @middleware
1222   end
1223 end
mime_type(type, value = nil) click to toggle source

Lookup or register a mime type in Rack’s mime registry.

     # File lib/sinatra/base.rb
1333 def mime_type(type, value = nil)
1334   return type      if type.nil?
1335   return type.to_s if type.to_s.include?('/')
1336   type = ".#{type}" unless type.to_s[0] == ?.
1337   return Rack::Mime.mime_type(type, nil) unless value
1338   Rack::Mime::MIME_TYPES[type] = value
1339 end
mime_types(type) click to toggle source

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
1344 def mime_types(type)
1345   type = mime_type type
1346   type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type]
1347 end
new(*args, &bk) click to toggle source

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
1491 def new(*args, &bk)
1492   instance = new!(*args, &bk)
1493   Wrapper.new(build(instance).to_app, instance)
1494 end
new!(app = nil)

Create a new instance without middleware in front of it.

Alias for: new
not_found(&block) click to toggle source

Sugar for ‘error(404) { … }`

     # File lib/sinatra/base.rb
1284 def not_found(&block)
1285   error(404, &block)
1286 end
options(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1401 def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end
patch(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1402 def patch(path, opts = {}, &bk)   route 'PATCH',   path, opts, &bk end
post(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1398 def post(path, opts = {}, &bk)    route 'POST',    path, opts, &bk end
production?() click to toggle source
     # File lib/sinatra/base.rb
1425 def production?;  environment == :production  end
prototype() click to toggle source

The prototype instance used to process requests.

     # File lib/sinatra/base.rb
1481 def prototype
1482   @prototype ||= new
1483 end
provides(*types) click to toggle source

Condition for matching mimetypes. Accepts file extensions.

     # File lib/sinatra/base.rb
1591 def provides(*types)
1592   types.map! { |t| mime_types(t) }
1593   types.flatten!
1594   condition do
1595     if type = response['Content-Type']
1596       types.include? type or types.include? type[/^[^;]+/]
1597     elsif type = request.preferred_type(types)
1598       params = (type.respond_to?(:params) ? type.params : {})
1599       content_type(type, params)
1600       true
1601     else
1602       false
1603     end
1604   end
1605 end
public=(value) click to toggle source
     # File lib/sinatra/base.rb
1374 def public=(value)
1375   warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead"
1376   set(:public_folder, value)
1377 end
public_dir() click to toggle source
     # File lib/sinatra/base.rb
1383 def public_dir
1384   public_folder
1385 end
public_dir=(value) click to toggle source
     # File lib/sinatra/base.rb
1379 def public_dir=(value)
1380   self.public_folder = value
1381 end
put(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1397 def put(path, opts = {}, &bk)     route 'PUT',     path, opts, &bk end
quit!() click to toggle source

Stop the self-hosted server if running.

     # File lib/sinatra/base.rb
1441 def quit!
1442   return unless running?
1443   # Use Thin's hard #stop! if available, otherwise just #stop.
1444   running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop
1445   $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless suppress_messages?
1446   set :running_server, nil
1447   set :handler_name, nil
1448 end
Also aliased as: stop!
register(*extensions, &block) click to toggle source

Register an extension. Alternatively take a block from which an extension will be created and registered on the fly.

     # File lib/sinatra/base.rb
1415 def register(*extensions, &block)
1416   extensions << Module.new(&block) if block_given?
1417   @extensions += extensions
1418   extensions.each do |extension|
1419     extend extension
1420     extension.registered(self) if extension.respond_to?(:registered)
1421   end
1422 end
reset!() click to toggle source

Removes all routes, filters, middleware and extension hooks from the current class (not routes/filters/… defined by its superclass).

     # File lib/sinatra/base.rb
1191 def reset!
1192   @conditions     = []
1193   @routes         = {}
1194   @filters        = {:before => [], :after => []}
1195   @errors         = {}
1196   @middleware     = []
1197   @prototype      = nil
1198   @extensions     = []
1199 
1200   if superclass.respond_to?(:templates)
1201     @templates = Hash.new { |hash, key| superclass.templates[key] }
1202   else
1203     @templates = {}
1204   end
1205 end
route(verb, path, options = {}, &block) click to toggle source
     # File lib/sinatra/base.rb
1607 def route(verb, path, options = {}, &block)
1608   enable :empty_path_info if path == "" and empty_path_info.nil?
1609   signature = compile!(verb, path, block, **options)
1610   (@routes[verb] ||= []) << signature
1611   invoke_hook(:route_added, verb, path, block)
1612   signature
1613 end
run!(options = {}, &block) click to toggle source

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
1455 def run!(options = {}, &block)
1456   return if running?
1457   set options
1458   handler         = detect_rack_handler
1459   handler_name    = handler.name.gsub(/.*::/, '')
1460   server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {}
1461   server_settings.merge!(:Port => port, :Host => bind)
1462 
1463   begin
1464     start_server(handler, server_settings, handler_name, &block)
1465   rescue Errno::EADDRINUSE
1466     $stderr.puts "== Someone is already performing on port #{port}!"
1467     raise
1468   ensure
1469     quit!
1470   end
1471 end
Also aliased as: start!
running?() click to toggle source

Check whether the self-hosted server is running or not.

     # File lib/sinatra/base.rb
1476 def running?
1477   running_server?
1478 end
set(option, value = (not_set = true), ignore_setter = false, &block) click to toggle source

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
1227 def set(option, value = (not_set = true), ignore_setter = false, &block)
1228   raise ArgumentError if block and !not_set
1229   value, not_set = block, false if block
1230 
1231   if not_set
1232     raise ArgumentError unless option.respond_to?(:each)
1233     option.each { |k,v| set(k, v) }
1234     return self
1235   end
1236 
1237   if respond_to?("#{option}=") and not ignore_setter
1238     return __send__("#{option}=", value)
1239   end
1240 
1241   setter = proc { |val| set option, val, true }
1242   getter = proc { value }
1243 
1244   case value
1245   when Proc
1246     getter = value
1247   when Symbol, Integer, FalseClass, TrueClass, NilClass
1248     getter = value.inspect
1249   when Hash
1250     setter = proc do |val|
1251       val = value.merge val if Hash === val
1252       set option, val, true
1253     end
1254   end
1255 
1256   define_singleton("#{option}=", setter)
1257   define_singleton(option, getter)
1258   define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?"
1259   self
1260 end
setup_common_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1676 def setup_common_logger(builder)
1677   builder.use Sinatra::CommonLogger
1678 end
setup_custom_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1680 def setup_custom_logger(builder)
1681   if logging.respond_to? :to_int
1682     builder.use Rack::Logger, logging
1683   else
1684     builder.use Rack::Logger
1685   end
1686 end
setup_default_middleware(builder) click to toggle source
     # File lib/sinatra/base.rb
1649 def setup_default_middleware(builder)
1650   builder.use ExtendedRack
1651   builder.use ShowExceptions       if show_exceptions?
1652   builder.use Rack::MethodOverride if method_override?
1653   builder.use Rack::Head
1654   setup_logging    builder
1655   setup_sessions   builder
1656   setup_protection builder
1657 end
setup_logging(builder) click to toggle source
     # File lib/sinatra/base.rb
1663 def setup_logging(builder)
1664   if logging?
1665     setup_common_logger(builder)
1666     setup_custom_logger(builder)
1667   elsif logging == false
1668     setup_null_logger(builder)
1669   end
1670 end
setup_middleware(builder) click to toggle source
     # File lib/sinatra/base.rb
1659 def setup_middleware(builder)
1660   middleware.each { |c,a,b| builder.use(c, *a, &b) }
1661 end
setup_null_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1672 def setup_null_logger(builder)
1673   builder.use Rack::NullLogger
1674 end
setup_protection(builder) click to toggle source
     # File lib/sinatra/base.rb
1688 def setup_protection(builder)
1689   return unless protection?
1690   options = Hash === protection ? protection.dup : {}
1691   options = {
1692     img_src:  "'self' data:",
1693     font_src: "'self'"
1694   }.merge options
1695 
1696   protect_session = options.fetch(:session) { sessions? }
1697   options[:without_session] = !protect_session
1698 
1699   options[:reaction] ||= :drop_session
1700 
1701   builder.use Rack::Protection, options
1702 end
setup_sessions(builder) click to toggle source
     # File lib/sinatra/base.rb
1704 def setup_sessions(builder)
1705   return unless sessions?
1706   options = {}
1707   options[:secret] = session_secret if session_secret?
1708   options.merge! sessions.to_hash if sessions.respond_to? :to_hash
1709   builder.use session_store, options
1710 end
setup_traps() click to toggle source
     # File lib/sinatra/base.rb
1548 def setup_traps
1549   if traps?
1550     at_exit { quit! }
1551 
1552     [:INT, :TERM].each do |signal|
1553       old_handler = trap(signal) do
1554         quit!
1555         old_handler.call if old_handler.respond_to?(:call)
1556       end
1557     end
1558 
1559     set :traps, false
1560   end
1561 end
start!(options = {}, &block)
Alias for: run!
start_server(handler, server_settings, handler_name) { |server| ... } click to toggle source

Starts the server by running the Rack Handler.

     # File lib/sinatra/base.rb
1525 def start_server(handler, server_settings, handler_name)
1526   # Ensure we initialize middleware before startup, to match standard Rack
1527   # behavior, by ensuring an instance exists:
1528   prototype
1529   # Run the instance we created:
1530   handler.run(self, server_settings) do |server|
1531     unless suppress_messages?
1532       $stderr.puts "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}"
1533     end
1534 
1535     setup_traps
1536     set :running_server, server
1537     set :handler_name,   handler_name
1538     server.threaded = settings.threaded if server.respond_to? :threaded=
1539 
1540     yield server if block_given?
1541   end
1542 end
stop!()
Alias for: quit!
suppress_messages?() click to toggle source
     # File lib/sinatra/base.rb
1544 def suppress_messages?
1545   handler_name =~ /cgi/i || quiet
1546 end
synchronize() { || ... } click to toggle source
     # File lib/sinatra/base.rb
1730 def synchronize(&block)
1731   if lock?
1732     @@mutex.synchronize(&block)
1733   else
1734     yield
1735   end
1736 end
template(name, &block) click to toggle source

Define a named template. The block must return the template source.

     # File lib/sinatra/base.rb
1289 def template(name, &block)
1290   filename, line = caller_locations.first
1291   templates[name] = [block, filename, line.to_i]
1292 end
test?() click to toggle source
     # File lib/sinatra/base.rb
1426 def test?;        environment == :test        end
use(middleware, *args, &block) click to toggle source

Use the specified Rack middleware

     # File lib/sinatra/base.rb
1435 def use(middleware, *args, &block)
1436   @prototype = nil
1437   @middleware << [middleware, args, block]
1438 end
user_agent(pattern) click to toggle source

Condition for matching user agent. Parameter should be Regexp. Will set params.

     # File lib/sinatra/base.rb
1578 def user_agent(pattern)
1579   condition do
1580     if request.user_agent.to_s =~ pattern
1581       @params[:agent] = $~[1..-1]
1582       true
1583     else
1584       false
1585     end
1586   end
1587 end
Also aliased as: agent
warn(message) click to toggle source

used for deprecation warnings

Calls superclass method
     # File lib/sinatra/base.rb
1739 def warn(message)
1740   super message + "\n\tfrom #{cleaned_caller.first.join(':')}"
1741 end

Public Instance Methods

call(env) click to toggle source

Rack call interface.

    # File lib/sinatra/base.rb
910 def call(env)
911   dup.call!(env)
912 end
forward() click to toggle source

Forward the request to the downstream app – middleware only.

    # File lib/sinatra/base.rb
967 def forward
968   fail "downstream app not set" unless @app.respond_to? :call
969   status, headers, body = @app.call env
970   @response.status = status
971   @response.body = body
972   @response.headers.merge! headers
973   nil
974 end
halt(*response) click to toggle source

Exit the current block, halts any further processing of the request, and returns the specified response.

    # File lib/sinatra/base.rb
954 def halt(*response)
955   response = response.first if response.length == 1
956   throw :halt, response
957 end
options() click to toggle source
    # File lib/sinatra/base.rb
946 def options
947   warn "Sinatra::Base#options is deprecated and will be removed, " \
948     "use #settings instead."
949   settings
950 end
pass(&block) click to toggle source

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
962 def pass(&block)
963   throw :pass, block
964 end
settings() click to toggle source

Access settings defined with Base.set.

    # File lib/sinatra/base.rb
942 def settings
943   self.class.settings
944 end

Private Instance Methods

dispatch!() click to toggle source

Dispatch a request with error handling.

     # File lib/sinatra/base.rb
1090 def dispatch!
1091   # Avoid passing frozen string in force_encoding
1092   @params.merge!(@request.params).each do |key, val|
1093     next unless val.respond_to?(:force_encoding)
1094     val = val.dup if val.frozen?
1095     @params[key] = force_encoding(val)
1096   end
1097 
1098   invoke do
1099     static! if settings.static? && (request.get? || request.head?)
1100     filter! :before
1101     route!
1102   end
1103 rescue ::Exception => boom
1104   invoke { handle_exception!(boom) }
1105 ensure
1106   begin
1107     filter! :after unless env['sinatra.static_file']
1108   rescue ::Exception => boom
1109     invoke { handle_exception!(boom) } unless @env['sinatra.error']
1110   end
1111 end
dump_errors!(boom) click to toggle source
     # File lib/sinatra/base.rb
1164 def dump_errors!(boom)
1165   msg = ["#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - #{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t")
1166   @env['rack.errors'].puts(msg)
1167 end
error_block!(key, *block_params) click to toggle source

Find an custom error block for the key(s) specified.

     # File lib/sinatra/base.rb
1149 def error_block!(key, *block_params)
1150   base = settings
1151   while base.respond_to?(:errors)
1152     next base = base.superclass unless args_array = base.errors[key]
1153     args_array.reverse_each do |args|
1154       first = args == args_array.first
1155       args += [block_params]
1156       resp = process_route(*args)
1157       return resp unless resp.nil? && !first
1158     end
1159   end
1160   return false unless key.respond_to? :superclass and key.superclass < Exception
1161   error_block!(key.superclass, *block_params)
1162 end
filter!(type, base = settings) click to toggle source

Run filters defined on the class and all superclasses.

    # File lib/sinatra/base.rb
979 def filter!(type, base = settings)
980   filter! type, base.superclass if base.superclass.respond_to?(:filters)
981   base.filters[type].each { |args| process_route(*args) }
982 end
force_encoding(*args) click to toggle source
     # File lib/sinatra/base.rb
1765 def force_encoding(*args) settings.force_encoding(*args) end
handle_exception!(boom) click to toggle source

Error handling during requests.

     # File lib/sinatra/base.rb
1114 def handle_exception!(boom)
1115   if error_params = @env['sinatra.error.params']
1116     @params = @params.merge(error_params)
1117   end
1118   @env['sinatra.error'] = boom
1119 
1120   http_status = if boom.kind_of? Sinatra::Error
1121     if boom.respond_to? :http_status
1122       boom.http_status
1123     elsif settings.use_code? && boom.respond_to?(:code)
1124       boom.code
1125     end
1126   end
1127 
1128   http_status = 500 unless http_status && http_status.between?(400, 599)
1129   status(http_status)
1130 
1131   boom_message = boom.message if boom.message && boom.message != boom.class.name
1132   if server_error?
1133     dump_errors! boom if settings.dump_errors?
1134     raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler
1135   elsif not_found?
1136     headers['X-Cascade'] = 'pass' if settings.x_cascade?
1137     body boom_message || '<h1>Not Found</h1>'
1138   elsif bad_request?
1139     body boom_message || '<h1>Bad Request</h1>'
1140   end
1141 
1142   res = error_block!(boom.class, boom) || error_block!(status, boom)
1143   return res if res or not server_error?
1144   raise boom if settings.raise_errors? or settings.show_exceptions?
1145   error_block! Exception, boom
1146 end
invoke() { || ... } click to toggle source

Run the block with ‘throw :halt’ support and apply result to the response.

     # File lib/sinatra/base.rb
1074 def invoke
1075   res = catch(:halt) { yield }
1076 
1077   res = [res] if Integer === res or String === res
1078   if Array === res and Integer === res.first
1079     res = res.dup
1080     status(res.shift)
1081     body(res.pop)
1082     headers(*res)
1083   elsif res.respond_to? :each
1084     body res
1085   end
1086   nil # avoid double setting the same response tuple twice
1087 end
process_route(pattern, conditions, block = nil, values = []) { |self, values| ... } click to toggle source

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
1017 def process_route(pattern, conditions, block = nil, values = [])
1018   route = @request.path_info
1019   route = '/' if route.empty? and not settings.empty_path_info?
1020   route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/')
1021   return unless params = pattern.params(route)
1022 
1023   params.delete("ignore") # TODO: better params handling, maybe turn it into "smart" object or detect changes
1024   force_encoding(params)
1025   @params = @params.merge(params) if params.any?
1026 
1027   regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? {|subpattern| subpattern.is_a?(Mustermann::Regular)} )
1028   if regexp_exists
1029     captures           = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c }
1030     values            += captures
1031     @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty?
1032   else
1033     values += params.values.flatten
1034   end
1035 
1036   catch(:pass) do
1037     conditions.each { |c| throw :pass if c.bind(self).call == false }
1038     block ? block[self, values] : yield(self, values)
1039   end
1040 rescue
1041   @env['sinatra.error.params'] = @params
1042   raise
1043 ensure
1044   params ||= {}
1045   params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params']
1046 end
route!(base = settings, pass_block = nil) click to toggle source

Run routes defined on the class and all superclasses.

     # File lib/sinatra/base.rb
 985 def route!(base = settings, pass_block = nil)
 986   if routes = base.routes[@request.request_method]
 987     routes.each do |pattern, conditions, block|
 988       returned_pass_block = process_route(pattern, conditions) do |*args|
 989         env['sinatra.route'] = "#{@request.request_method} #{pattern}"
 990         route_eval { block[*args] }
 991       end
 992 
 993       # don't wipe out pass_block in superclass
 994       pass_block = returned_pass_block if returned_pass_block
 995     end
 996   end
 997 
 998   # Run routes defined in superclass.
 999   if base.superclass.respond_to?(:routes)
1000     return route!(base.superclass, pass_block)
1001   end
1002 
1003   route_eval(&pass_block) if pass_block
1004   route_missing
1005 end
route_eval() { || ... } click to toggle source

Run a route block and throw :halt with the result.

     # File lib/sinatra/base.rb
1008 def route_eval
1009   throw :halt, yield
1010 end
route_missing() click to toggle source

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
1053 def route_missing
1054   if @app
1055     forward
1056   else
1057     raise NotFound, "#{request.request_method} #{request.path_info}"
1058   end
1059 end
static!(options = {}) click to toggle source

Attempt to serve static files from public directory. Throws :halt when a matching file is found, returns nil otherwise.

     # File lib/sinatra/base.rb
1063 def static!(options = {})
1064   return if (public_dir = settings.public_folder).nil?
1065   path = File.expand_path("#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" )
1066   return unless File.file?(path)
1067 
1068   env['sinatra.static_file'] = path
1069   cache_control(*settings.static_cache_control) if settings.static_cache_control?
1070   send_file path, options.merge(:disposition => nil)
1071 end