Class: Sinatra::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatra/router.rb

Overview

A Sinatra router that allows multiple Sinatra applications to be composed together.

Instance Method Summary collapse

Constructor Details

#initialize(app = nil, *_args, &block) ⇒ Router

Returns a new instance of Router.



7
8
9
10
11
12
13
14
15
# File 'lib/sinatra/router.rb', line 7

def initialize(app = nil, *_args, &block)
  @app        = app
  @apps       = []
  @conditions = []
  @run        = nil

  instance_eval(&block) if block
  @routes = build_routing_table
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/sinatra/router.rb', line 17

def call(env)
  if (ret = try_route(env['REQUEST_METHOD'], env['PATH_INFO'], env))
    ret
  else
    if !@app && !@run
      raise 'router needs to be (1) mounted as middleware or (b) contain ' \
            'a default run statement'
    end

    # if set as middlware, prefer that, otherwise try default run module
    (@app || @run).call(env)
  end
end

#mount(app, *conditions) ⇒ Object



38
39
40
41
# File 'lib/sinatra/router.rb', line 38

def mount(app, *conditions)
  # mix in context based conditions with conditions given by parameter
  @apps << [app, @conditions + conditions]
end

#run(app) ⇒ Object

specify the default app to run if no other app routes matched



32
33
34
35
36
# File 'lib/sinatra/router.rb', line 32

def run(app)
  raise '@run already set' if @run

  @run = app
end

#version(version, &block) ⇒ Object

yield to a builder block in which all defined apps will only respond for the given version



45
46
47
48
49
# File 'lib/sinatra/router.rb', line 45

def version(version, &block)
  @conditions = { version: version }
  instance_eval(&block) if block
  @conditions = {}
end