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
906 def initialize(app = nil)
907   super()
908   @app = app
909   @template_cache = Tilt::Cache.new
910   yield self if block_given?
911 end
Also aliased as: new!
settings() click to toggle source

Access settings defined with Base.set.

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

Private Class Methods

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

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
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
1363 def after(path = /.*/, **options, &block)
1364   add_filter(:after, path, **options, &block)
1365 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
1356 def before(path = /.*/, **options, &block)
1357   add_filter(:before, path, **options, &block)
1358 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
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
call(env) click to toggle source
     # File lib/sinatra/base.rb
1510 def call(env)
1511   synchronize { prototype.call(env) }
1512 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
1516 def caller_files
1517   cleaned_caller(1).flatten
1518 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
1522 def caller_locations
1523   cleaned_caller 2
1524 end
cleaned_caller(keep = 3) click to toggle source

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
compile(path, route_mustermann_opts = {}) click to toggle source
     # File lib/sinatra/base.rb
1649 def compile(path, route_mustermann_opts = {})
1650   Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts))
1651 end
compile!(verb, path, block, **options) click to toggle source
     # 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
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
1374 def condition(name = "#{caller.first[/`.*'/]} condition", &block)
1375   @conditions << generate_method(name, &block)
1376 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
1434 def configure(*envs)
1435   yield self if envs.empty? || envs.include?(environment.to_sym)
1436 end
define_singleton(name, content = Proc.new) click to toggle source

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
delete(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1403 def delete(path, opts = {}, &bk)  route 'DELETE',  path, opts, &bk end
detect_rack_handler() click to toggle source
     # 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
development?() click to toggle source
     # File lib/sinatra/base.rb
1428 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
1272 def disable(*opts)
1273   opts.each { |key| set(key, false) }
1274 end
enable(*opts) click to toggle source

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
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
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
extensions() click to toggle source

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_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
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
generate_method(method_name, &block) click to toggle source
     # 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
get(path, opts = {}, &block) click to toggle source

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
head(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1404 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
1412 def helpers(*extensions, &block)
1413   class_eval(&block)   if block_given?
1414   include(*extensions) if extensions.any?
1415 end
host_name(pattern) click to toggle source

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
inherited(subclass) click to toggle source
Calls superclass method
     # 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
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
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
invoke_hook(name, *args) click to toggle source
     # 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
layout(name = :layout, &block) click to toggle source

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
middleware() click to toggle source

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
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
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
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
1348 def mime_types(type)
1349   type = mime_type type
1350   type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type]
1351 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
1495 def new(*args, &bk)
1496   instance = new!(*args, &bk)
1497   Wrapper.new(build(instance).to_app, instance)
1498 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
1288 def not_found(&block)
1289   error(404, &block)
1290 end
options(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1405 def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end
patch(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1406 def patch(path, opts = {}, &bk)   route 'PATCH',   path, opts, &bk end
post(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1402 def post(path, opts = {}, &bk)    route 'POST',    path, opts, &bk end
production?() click to toggle source
     # File lib/sinatra/base.rb
1429 def production?;  environment == :production  end
prototype() click to toggle source

The prototype instance used to process requests.

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

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
public=(value) click to toggle source
     # 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
public_dir() click to toggle source
     # File lib/sinatra/base.rb
1387 def public_dir
1388   public_folder
1389 end
public_dir=(value) click to toggle source
     # File lib/sinatra/base.rb
1383 def public_dir=(value)
1384   self.public_folder = value
1385 end
put(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1401 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
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
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
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
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
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
route(verb, path, options = {}, &block) click to toggle source
     # 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!(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
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
Also aliased as: start!
running?() click to toggle source

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

     # File lib/sinatra/base.rb
1480 def running?
1481   running_server?
1482 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
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
setup_common_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1680 def setup_common_logger(builder)
1681   builder.use Sinatra::CommonLogger
1682 end
setup_custom_logger(builder) click to toggle source
     # 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
setup_default_middleware(builder) click to toggle source
     # 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
setup_logging(builder) click to toggle source
     # 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
setup_middleware(builder) click to toggle source
     # File lib/sinatra/base.rb
1663 def setup_middleware(builder)
1664   middleware.each { |c,a,b| builder.use(c, *a, &b) }
1665 end
setup_null_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1676 def setup_null_logger(builder)
1677   builder.use Rack::NullLogger
1678 end
setup_protection(builder) click to toggle source
     # 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
setup_sessions(builder) click to toggle source
     # 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
setup_traps() click to toggle source
     # 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
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
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
stop!()
Alias for: quit!
suppress_messages?() click to toggle source
     # File lib/sinatra/base.rb
1548 def suppress_messages?
1549   handler_name =~ /cgi/i || quiet
1550 end
synchronize() { || ... } click to toggle source
     # File lib/sinatra/base.rb
1734 def synchronize(&block)
1735   if lock?
1736     @@mutex.synchronize(&block)
1737   else
1738     yield
1739   end
1740 end
template(name, &block) click to toggle source

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
test?() click to toggle source
     # File lib/sinatra/base.rb
1430 def test?;        environment == :test        end
use(middleware, *args, &block) click to toggle source

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
user_agent(pattern) click to toggle source

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
Also aliased as: agent
warn(message) click to toggle source

used for deprecation warnings

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

Public Instance Methods

call(env) click to toggle source

Rack call interface.

    # File lib/sinatra/base.rb
914 def call(env)
915   dup.call!(env)
916 end
forward() click to toggle source

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
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
958 def halt(*response)
959   response = response.first if response.length == 1
960   throw :halt, response
961 end
options() click to toggle source
    # 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(&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
966 def pass(&block)
967   throw :pass, block
968 end
settings() click to toggle source

Access settings defined with Base.set.

    # File lib/sinatra/base.rb
946 def settings
947   self.class.settings
948 end

Private Instance Methods

dispatch!() click to toggle source

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
dump_errors!(boom) click to toggle source
     # 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
error_block!(key, *block_params) click to toggle source

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
filter!(type, base = settings) click to toggle source

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
force_encoding(*args) click to toggle source
     # File lib/sinatra/base.rb
1769 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
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
invoke() { || ... } click to toggle source

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
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
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
route!(base = settings, pass_block = nil) click to toggle source

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
route_eval() { || ... } click to toggle source

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
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
1057 def route_missing
1058   if @app
1059     forward
1060   else
1061     raise NotFound, "#{request.request_method} #{request.path_info}"
1062   end
1063 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
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