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
899 def initialize(app = nil)
900   super()
901   @app = app
902   @template_cache = Tilt::Cache.new
903   yield self if block_given?
904 end
Also aliased as: new!
settings() click to toggle source

Access settings defined with Base.set.

    # File lib/sinatra/base.rb
934 def self.settings
935   self
936 end

Private Class Methods

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

add a filter

     # File lib/sinatra/base.rb
1360 def add_filter(type, path = /.*/, **options, &block)
1361   filters[type] << compile!(type, path, block, **options)
1362 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
1355 def after(path = /.*/, **options, &block)
1356   add_filter(:after, path, **options, &block)
1357 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
1348 def before(path = /.*/, **options, &block)
1349   add_filter(:before, path, **options, &block)
1350 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
1494 def build(app)
1495   builder = Rack::Builder.new
1496   setup_default_middleware builder
1497   setup_middleware builder
1498   builder.run app
1499   builder
1500 end
call(env) click to toggle source
     # File lib/sinatra/base.rb
1502 def call(env)
1503   synchronize { prototype.call(env) }
1504 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
1508 def caller_files
1509   cleaned_caller(1).flatten
1510 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
1514 def caller_locations
1515   cleaned_caller 2
1516 end
cleaned_caller(keep = 3) click to toggle source

Like Kernel#caller but excluding certain magic entries

     # File lib/sinatra/base.rb
1740 def cleaned_caller(keep = 3)
1741   caller(1).
1742     map!    { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }.
1743     reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } }
1744 end
compile(path, route_mustermann_opts = {}) click to toggle source
     # File lib/sinatra/base.rb
1641 def compile(path, route_mustermann_opts = {})
1642   Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts))
1643 end
compile!(verb, path, block, **options) click to toggle source
     # File lib/sinatra/base.rb
1622 def compile!(verb, path, block, **options)
1623   # Because of self.options.host
1624   host_name(options.delete(:host)) if options.key?(:host)
1625   # Pass Mustermann opts to compile()
1626   route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze
1627 
1628   options.each_pair { |option, args| send(option, *args) }
1629 
1630   pattern                 = compile(path, route_mustermann_opts)
1631   method_name             = "#{verb} #{path}"
1632   unbound_method          = generate_method(method_name, &block)
1633   conditions, @conditions = @conditions, []
1634   wrapper                 = block.arity != 0 ?
1635     proc { |a, p| unbound_method.bind(a).call(*p) } :
1636     proc { |a, p| unbound_method.bind(a).call }
1637 
1638   [ pattern, conditions, wrapper ]
1639 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
1366 def condition(name = "#{caller.first[/`.*'/]} condition", &block)
1367   @conditions << generate_method(name, &block)
1368 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
1426 def configure(*envs)
1427   yield self if envs.empty? || envs.include?(environment.to_sym)
1428 end
define_singleton(name, content = Proc.new) click to toggle source

Dynamically defines a method on settings.

     # File lib/sinatra/base.rb
1560 def define_singleton(name, content = Proc.new)
1561   singleton_class.class_eval do
1562     undef_method(name) if method_defined? name
1563     String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content)
1564   end
1565 end
delete(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1395 def delete(path, opts = {}, &bk)  route 'DELETE',  path, opts, &bk end
detect_rack_handler() click to toggle source
     # File lib/sinatra/base.rb
1708 def detect_rack_handler
1709   servers = Array(server)
1710   servers.each do |server_name|
1711     begin
1712       return Rack::Handler.get(server_name.to_s)
1713     rescue LoadError, NameError
1714     end
1715   end
1716   fail "Server handler (#{servers.join(',')}) not found."
1717 end
development?() click to toggle source
     # File lib/sinatra/base.rb
1420 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
1264 def disable(*opts)
1265   opts.each { |key| set(key, false) }
1266 end
enable(*opts) click to toggle source

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

     # File lib/sinatra/base.rb
1259 def enable(*opts)
1260   opts.each { |key| set(key, true) }
1261 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
1271 def error(*codes, &block)
1272   args  = compile! "ERROR", /.*/, block
1273   codes = codes.flat_map(&method(:Array))
1274   codes << Exception if codes.empty?
1275   codes << Sinatra::NotFound if codes.include?(404)
1276   codes.each { |c| (@errors[c] ||= []) << args }
1277 end
extensions() click to toggle source

Extension modules registered on this class and all superclasses.

     # File lib/sinatra/base.rb
1204 def extensions
1205   if superclass.respond_to?(:extensions)
1206     (@extensions + superclass.extensions).uniq
1207   else
1208     @extensions
1209   end
1210 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
1749 def self.force_encoding(data, encoding = default_encoding)
1750   return if data == settings || data.is_a?(Tempfile)
1751   if data.respond_to? :force_encoding
1752     data.force_encoding(encoding).encode!
1753   elsif data.respond_to? :each_value
1754     data.each_value { |v| force_encoding(v, encoding) }
1755   elsif data.respond_to? :each
1756     data.each { |v| force_encoding(v, encoding) }
1757   end
1758   data
1759 end
generate_method(method_name, &block) click to toggle source
     # File lib/sinatra/base.rb
1615 def generate_method(method_name, &block)
1616   define_method(method_name, &block)
1617   method = instance_method method_name
1618   remove_method method_name
1619   method
1620 end
get(path, opts = {}, &block) click to toggle source

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

     # File lib/sinatra/base.rb
1385 def get(path, opts = {}, &block)
1386   conditions = @conditions.dup
1387   route('GET', path, opts, &block)
1388 
1389   @conditions = conditions
1390   route('HEAD', path, opts, &block)
1391 end
head(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1396 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
1404 def helpers(*extensions, &block)
1405   class_eval(&block)   if block_given?
1406   include(*extensions) if extensions.any?
1407 end
host_name(pattern) click to toggle source

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

     # File lib/sinatra/base.rb
1568 def host_name(pattern)
1569   condition { pattern === request.host }
1570 end
inherited(subclass) click to toggle source
Calls superclass method
     # File lib/sinatra/base.rb
1719 def inherited(subclass)
1720   subclass.reset!
1721   subclass.set :app_file, caller_files.first unless subclass.app_file?
1722   super
1723 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
1297 def inline_templates=(file = nil)
1298   file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file
1299 
1300   begin
1301     io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file)
1302     app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2)
1303   rescue Errno::ENOENT
1304     app, data = nil
1305   end
1306 
1307   if data
1308     if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m
1309       encoding = $2
1310     else
1311       encoding = settings.default_encoding
1312     end
1313     lines = app.count("\n") + 1
1314     template = nil
1315     force_encoding data, encoding
1316     data.each_line do |line|
1317       lines += 1
1318       if line =~ /^@@\s*(.*\S)\s*$/
1319         template = force_encoding(String.new, encoding)
1320         templates[$1.to_sym] = [template, file, lines]
1321       elsif template
1322         template << line
1323       end
1324     end
1325   end
1326 end
invoke_hook(name, *args) click to toggle source
     # File lib/sinatra/base.rb
1611 def invoke_hook(name, *args)
1612   extensions.each { |e| e.send(name, *args) if e.respond_to?(name) }
1613 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
1291 def layout(name = :layout, &block)
1292   template name, &block
1293 end
middleware() click to toggle source

Middleware used in this class and all superclasses.

     # File lib/sinatra/base.rb
1213 def middleware
1214   if superclass.respond_to?(:middleware)
1215     superclass.middleware + @middleware
1216   else
1217     @middleware
1218   end
1219 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
1329 def mime_type(type, value = nil)
1330   return type      if type.nil?
1331   return type.to_s if type.to_s.include?('/')
1332   type = ".#{type}" unless type.to_s[0] == ?.
1333   return Rack::Mime.mime_type(type, nil) unless value
1334   Rack::Mime::MIME_TYPES[type] = value
1335 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
1340 def mime_types(type)
1341   type = mime_type type
1342   type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type]
1343 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
1487 def new(*args, &bk)
1488   instance = new!(*args, &bk)
1489   Wrapper.new(build(instance).to_app, instance)
1490 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
1280 def not_found(&block)
1281   error(404, &block)
1282 end
options(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1397 def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end
patch(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1398 def patch(path, opts = {}, &bk)   route 'PATCH',   path, opts, &bk end
post(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1394 def post(path, opts = {}, &bk)    route 'POST',    path, opts, &bk end
production?() click to toggle source
     # File lib/sinatra/base.rb
1421 def production?;  environment == :production  end
prototype() click to toggle source

The prototype instance used to process requests.

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

Condition for matching mimetypes. Accepts file extensions.

     # File lib/sinatra/base.rb
1587 def provides(*types)
1588   types.map! { |t| mime_types(t) }
1589   types.flatten!
1590   condition do
1591     if type = response['Content-Type']
1592       types.include? type or types.include? type[/^[^;]+/]
1593     elsif type = request.preferred_type(types)
1594       params = (type.respond_to?(:params) ? type.params : {})
1595       content_type(type, params)
1596       true
1597     else
1598       false
1599     end
1600   end
1601 end
public=(value) click to toggle source
     # File lib/sinatra/base.rb
1370 def public=(value)
1371   warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead"
1372   set(:public_folder, value)
1373 end
public_dir() click to toggle source
     # File lib/sinatra/base.rb
1379 def public_dir
1380   public_folder
1381 end
public_dir=(value) click to toggle source
     # File lib/sinatra/base.rb
1375 def public_dir=(value)
1376   self.public_folder = value
1377 end
put(path, opts = {}, &bk) click to toggle source
     # File lib/sinatra/base.rb
1393 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
1437 def quit!
1438   return unless running?
1439   # Use Thin's hard #stop! if available, otherwise just #stop.
1440   running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop
1441   $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless suppress_messages?
1442   set :running_server, nil
1443   set :handler_name, nil
1444 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
1411 def register(*extensions, &block)
1412   extensions << Module.new(&block) if block_given?
1413   @extensions += extensions
1414   extensions.each do |extension|
1415     extend extension
1416     extension.registered(self) if extension.respond_to?(:registered)
1417   end
1418 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
1187 def reset!
1188   @conditions     = []
1189   @routes         = {}
1190   @filters        = {:before => [], :after => []}
1191   @errors         = {}
1192   @middleware     = []
1193   @prototype      = nil
1194   @extensions     = []
1195 
1196   if superclass.respond_to?(:templates)
1197     @templates = Hash.new { |hash, key| superclass.templates[key] }
1198   else
1199     @templates = {}
1200   end
1201 end
route(verb, path, options = {}, &block) click to toggle source
     # File lib/sinatra/base.rb
1603 def route(verb, path, options = {}, &block)
1604   enable :empty_path_info if path == "" and empty_path_info.nil?
1605   signature = compile!(verb, path, block, **options)
1606   (@routes[verb] ||= []) << signature
1607   invoke_hook(:route_added, verb, path, block)
1608   signature
1609 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
1451 def run!(options = {}, &block)
1452   return if running?
1453   set options
1454   handler         = detect_rack_handler
1455   handler_name    = handler.name.gsub(/.*::/, '')
1456   server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {}
1457   server_settings.merge!(:Port => port, :Host => bind)
1458 
1459   begin
1460     start_server(handler, server_settings, handler_name, &block)
1461   rescue Errno::EADDRINUSE
1462     $stderr.puts "== Someone is already performing on port #{port}!"
1463     raise
1464   ensure
1465     quit!
1466   end
1467 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
1472 def running?
1473   running_server?
1474 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
1223 def set(option, value = (not_set = true), ignore_setter = false, &block)
1224   raise ArgumentError if block and !not_set
1225   value, not_set = block, false if block
1226 
1227   if not_set
1228     raise ArgumentError unless option.respond_to?(:each)
1229     option.each { |k,v| set(k, v) }
1230     return self
1231   end
1232 
1233   if respond_to?("#{option}=") and not ignore_setter
1234     return __send__("#{option}=", value)
1235   end
1236 
1237   setter = proc { |val| set option, val, true }
1238   getter = proc { value }
1239 
1240   case value
1241   when Proc
1242     getter = value
1243   when Symbol, Integer, FalseClass, TrueClass, NilClass
1244     getter = value.inspect
1245   when Hash
1246     setter = proc do |val|
1247       val = value.merge val if Hash === val
1248       set option, val, true
1249     end
1250   end
1251 
1252   define_singleton("#{option}=", setter)
1253   define_singleton(option, getter)
1254   define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?"
1255   self
1256 end
setup_common_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1672 def setup_common_logger(builder)
1673   builder.use Sinatra::CommonLogger
1674 end
setup_custom_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1676 def setup_custom_logger(builder)
1677   if logging.respond_to? :to_int
1678     builder.use Rack::Logger, logging
1679   else
1680     builder.use Rack::Logger
1681   end
1682 end
setup_default_middleware(builder) click to toggle source
     # File lib/sinatra/base.rb
1645 def setup_default_middleware(builder)
1646   builder.use ExtendedRack
1647   builder.use ShowExceptions       if show_exceptions?
1648   builder.use Rack::MethodOverride if method_override?
1649   builder.use Rack::Head
1650   setup_logging    builder
1651   setup_sessions   builder
1652   setup_protection builder
1653 end
setup_logging(builder) click to toggle source
     # File lib/sinatra/base.rb
1659 def setup_logging(builder)
1660   if logging?
1661     setup_common_logger(builder)
1662     setup_custom_logger(builder)
1663   elsif logging == false
1664     setup_null_logger(builder)
1665   end
1666 end
setup_middleware(builder) click to toggle source
     # File lib/sinatra/base.rb
1655 def setup_middleware(builder)
1656   middleware.each { |c,a,b| builder.use(c, *a, &b) }
1657 end
setup_null_logger(builder) click to toggle source
     # File lib/sinatra/base.rb
1668 def setup_null_logger(builder)
1669   builder.use Rack::NullLogger
1670 end
setup_protection(builder) click to toggle source
     # File lib/sinatra/base.rb
1684 def setup_protection(builder)
1685   return unless protection?
1686   options = Hash === protection ? protection.dup : {}
1687   options = {
1688     img_src:  "'self' data:",
1689     font_src: "'self'"
1690   }.merge options
1691 
1692   protect_session = options.fetch(:session) { sessions? }
1693   options[:without_session] = !protect_session
1694 
1695   options[:reaction] ||= :drop_session
1696 
1697   builder.use Rack::Protection, options
1698 end
setup_sessions(builder) click to toggle source
     # File lib/sinatra/base.rb
1700 def setup_sessions(builder)
1701   return unless sessions?
1702   options = {}
1703   options[:secret] = session_secret if session_secret?
1704   options.merge! sessions.to_hash if sessions.respond_to? :to_hash
1705   builder.use session_store, options
1706 end
setup_traps() click to toggle source
     # File lib/sinatra/base.rb
1544 def setup_traps
1545   if traps?
1546     at_exit { quit! }
1547 
1548     [:INT, :TERM].each do |signal|
1549       old_handler = trap(signal) do
1550         quit!
1551         old_handler.call if old_handler.respond_to?(:call)
1552       end
1553     end
1554 
1555     set :traps, false
1556   end
1557 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
1521 def start_server(handler, server_settings, handler_name)
1522   # Ensure we initialize middleware before startup, to match standard Rack
1523   # behavior, by ensuring an instance exists:
1524   prototype
1525   # Run the instance we created:
1526   handler.run(self, server_settings) do |server|
1527     unless suppress_messages?
1528       $stderr.puts "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}"
1529     end
1530 
1531     setup_traps
1532     set :running_server, server
1533     set :handler_name,   handler_name
1534     server.threaded = settings.threaded if server.respond_to? :threaded=
1535 
1536     yield server if block_given?
1537   end
1538 end
stop!()
Alias for: quit!
suppress_messages?() click to toggle source
     # File lib/sinatra/base.rb
1540 def suppress_messages?
1541   handler_name =~ /cgi/i || quiet
1542 end
synchronize() { || ... } click to toggle source
     # File lib/sinatra/base.rb
1726 def synchronize(&block)
1727   if lock?
1728     @@mutex.synchronize(&block)
1729   else
1730     yield
1731   end
1732 end
template(name, &block) click to toggle source

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

     # File lib/sinatra/base.rb
1285 def template(name, &block)
1286   filename, line = caller_locations.first
1287   templates[name] = [block, filename, line.to_i]
1288 end
test?() click to toggle source
     # File lib/sinatra/base.rb
1422 def test?;        environment == :test        end
use(middleware, *args, &block) click to toggle source

Use the specified Rack middleware

     # File lib/sinatra/base.rb
1431 def use(middleware, *args, &block)
1432   @prototype = nil
1433   @middleware << [middleware, args, block]
1434 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
1574 def user_agent(pattern)
1575   condition do
1576     if request.user_agent.to_s =~ pattern
1577       @params[:agent] = $~[1..-1]
1578       true
1579     else
1580       false
1581     end
1582   end
1583 end
Also aliased as: agent
warn(message) click to toggle source

used for deprecation warnings

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

Public Instance Methods

call(env) click to toggle source

Rack call interface.

    # File lib/sinatra/base.rb
907 def call(env)
908   dup.call!(env)
909 end
forward() click to toggle source

Forward the request to the downstream app – middleware only.

    # File lib/sinatra/base.rb
964 def forward
965   fail "downstream app not set" unless @app.respond_to? :call
966   status, headers, body = @app.call env
967   @response.status = status
968   @response.body = body
969   @response.headers.merge! headers
970   nil
971 end
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
951 def halt(*response)
952   response = response.first if response.length == 1
953   throw :halt, response
954 end
options() click to toggle source
    # File lib/sinatra/base.rb
943 def options
944   warn "Sinatra::Base#options is deprecated and will be removed, " \
945     "use #settings instead."
946   settings
947 end
pass(&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
959 def pass(&block)
960   throw :pass, block
961 end
settings() click to toggle source

Access settings defined with Base.set.

    # File lib/sinatra/base.rb
939 def settings
940   self.class.settings
941 end

Private Instance Methods

dispatch!() click to toggle source

Dispatch a request with error handling.

     # File lib/sinatra/base.rb
1087 def dispatch!
1088   # Avoid passing frozen string in force_encoding
1089   @params.merge!(@request.params).each do |key, val|
1090     next unless val.respond_to?(:force_encoding)
1091     val = val.dup if val.frozen?
1092     @params[key] = force_encoding(val)
1093   end
1094 
1095   invoke do
1096     static! if settings.static? && (request.get? || request.head?)
1097     filter! :before
1098     route!
1099   end
1100 rescue ::Exception => boom
1101   invoke { handle_exception!(boom) }
1102 ensure
1103   begin
1104     filter! :after unless env['sinatra.static_file']
1105   rescue ::Exception => boom
1106     invoke { handle_exception!(boom) } unless @env['sinatra.error']
1107   end
1108 end
dump_errors!(boom) click to toggle source
     # File lib/sinatra/base.rb
1160 def dump_errors!(boom)
1161   msg = ["#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - #{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t")
1162   @env['rack.errors'].puts(msg)
1163 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
1145 def error_block!(key, *block_params)
1146   base = settings
1147   while base.respond_to?(:errors)
1148     next base = base.superclass unless args_array = base.errors[key]
1149     args_array.reverse_each do |args|
1150       first = args == args_array.first
1151       args += [block_params]
1152       resp = process_route(*args)
1153       return resp unless resp.nil? && !first
1154     end
1155   end
1156   return false unless key.respond_to? :superclass and key.superclass < Exception
1157   error_block!(key.superclass, *block_params)
1158 end
filter!(type, base = settings) click to toggle source

Run filters defined on the class and all superclasses.

    # File lib/sinatra/base.rb
976 def filter!(type, base = settings)
977   filter! type, base.superclass if base.superclass.respond_to?(:filters)
978   base.filters[type].each { |args| process_route(*args) }
979 end
force_encoding(*args) click to toggle source
     # File lib/sinatra/base.rb
1761 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
1111 def handle_exception!(boom)
1112   if error_params = @env['sinatra.error.params']
1113     @params = @params.merge(error_params)
1114   end
1115   @env['sinatra.error'] = boom
1116 
1117   if boom.respond_to? :http_status
1118     status(boom.http_status)
1119   elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599
1120     status(boom.code)
1121   else
1122     status(500)
1123   end
1124 
1125   status(500) unless status.between? 400, 599
1126 
1127   boom_message = boom.message if boom.message && boom.message != boom.class.name
1128   if server_error?
1129     dump_errors! boom if settings.dump_errors?
1130     raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler
1131   elsif not_found?
1132     headers['X-Cascade'] = 'pass' if settings.x_cascade?
1133     body boom_message || '<h1>Not Found</h1>'
1134   elsif bad_request?
1135     body boom_message || '<h1>Bad Request</h1>'
1136   end
1137 
1138   res = error_block!(boom.class, boom) || error_block!(status, boom)
1139   return res if res or not server_error?
1140   raise boom if settings.raise_errors? or settings.show_exceptions?
1141   error_block! Exception, boom
1142 end
invoke() { || ... } click to toggle source

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

     # File lib/sinatra/base.rb
1071 def invoke
1072   res = catch(:halt) { yield }
1073 
1074   res = [res] if Integer === res or String === res
1075   if Array === res and Integer === res.first
1076     res = res.dup
1077     status(res.shift)
1078     body(res.pop)
1079     headers(*res)
1080   elsif res.respond_to? :each
1081     body res
1082   end
1083   nil # avoid double setting the same response tuple twice
1084 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
1014 def process_route(pattern, conditions, block = nil, values = [])
1015   route = @request.path_info
1016   route = '/' if route.empty? and not settings.empty_path_info?
1017   route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/')
1018   return unless params = pattern.params(route)
1019 
1020   params.delete("ignore") # TODO: better params handling, maybe turn it into "smart" object or detect changes
1021   force_encoding(params)
1022   @params = @params.merge(params) if params.any?
1023 
1024   regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? {|subpattern| subpattern.is_a?(Mustermann::Regular)} )
1025   if regexp_exists
1026     captures           = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c }
1027     values            += captures
1028     @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty?
1029   else
1030     values += params.values.flatten
1031   end
1032 
1033   catch(:pass) do
1034     conditions.each { |c| throw :pass if c.bind(self).call == false }
1035     block ? block[self, values] : yield(self, values)
1036   end
1037 rescue
1038   @env['sinatra.error.params'] = @params
1039   raise
1040 ensure
1041   params ||= {}
1042   params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params']
1043 end
route!(base = settings, pass_block = nil) click to toggle source

Run routes defined on the class and all superclasses.

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

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

     # File lib/sinatra/base.rb
1005 def route_eval
1006   throw :halt, yield
1007 end
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
1050 def route_missing
1051   if @app
1052     forward
1053   else
1054     raise NotFound, "#{request.request_method} #{request.path_info}"
1055   end
1056 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
1060 def static!(options = {})
1061   return if (public_dir = settings.public_folder).nil?
1062   path = File.expand_path("#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" )
1063   return unless File.file?(path)
1064 
1065   env['sinatra.static_file'] = path
1066   cache_control(*settings.static_cache_control) if settings.static_cache_control?
1067   send_file path, options.merge(:disposition => nil)
1068 end