chneukirchen / rack-mirror

OUTDATED mirror of Rack's darcs repository, use github.com/chneukirchen/rack

This URL has Read+Write access

chneukirchen (author)
Sat May 24 08:54:49 -0700 2008
commit  5a117d0b45b4ed2785a714eaa060e8c66512c4c3
tree    0942c84f57f557d899fa767e06ca37a196563185
parent  ed86dfd676dcb46e276b6906f017df514e5632f9 parent  ebdd511d332d2b6cd33bda7bb4777518cfc89fa4
rack-mirror / lib / rack / builder.rb
100644 57 lines (50 sloc) 1.282 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module Rack
  # Rack::Builder implements a small DSL to iteratively construct Rack
  # applications.
  #
  # Example:
  #
  # app = Rack::Builder.new {
  # use Rack::CommonLogger
  # use Rack::ShowExceptions
  # map "/lobster" do
  # use Rack::Lint
  # run Rack::Lobster.new
  # end
  # }
  #
  # +use+ adds a middleware to the stack, +run+ dispatches to an application.
  # You can use +map+ to construct a Rack::URLMap in a convenient way.
 
  class Builder
    def initialize(&block)
      @ins = []
      instance_eval(&block)
    end
 
    def use(middleware, *args, &block)
      @ins << if block_given?
        lambda { |app| middleware.new(app, *args, &block) }
      else
        lambda { |app| middleware.new(app, *args) }
      end
    end
 
    def run(app)
      @ins << app #lambda { |nothing| app }
    end
 
    def map(path, &block)
      if @ins.last.kind_of? Hash
        @ins.last[path] = Rack::Builder.new(&block).to_app
      else
        @ins << {}
        map(path, &block)
      end
    end
 
    def to_app
      @ins[-1] = Rack::URLMap.new(@ins.last) if Hash === @ins.last
      inner_app = @ins.last
      @ins[0...-1].reverse.inject(inner_app) { |a, e| e.call(a) }
    end
 
    def call(env)
      to_app.call(env)
    end
  end
end