Sha256: 70e9a6a04dcb76c00ffa0e4a31dd8fb88d86b085466cb6463a099d07fc352264

Contents?: true

Size: 1.38 KB

Versions: 27

Compression:

Stored size: 1.38 KB

Contents

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
  #  }
  #
  # Or
  #
  #  app = Rack::Builder.app do
  #    use Rack::CommonLogger
  #    lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'OK'] }
  #  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) if block_given?
    end

    def self.app(&block)
      self.new(&block).to_app
    end

    def use(middleware, *args, &block)
      @ins << lambda { |app| middleware.new(app, *args, &block) }
    end

    def run(app)
      @ins << app #lambda { |nothing| app }
    end

    def map(path, &block)
      if @ins.last.kind_of? Hash
        @ins.last[path] = self.class.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

Version data entries

27 entries across 27 versions & 12 rubygems

Version Path
kjvarga-rack-1.0.0 lib/rack/builder.rb
qoobaa-rack-1.0.0.1 lib/rack/builder.rb
qoobaa-rack-1.0.2 lib/rack/builder.rb
timocratic-rack-1.0.0 lib/rack/builder.rb
middleman-0.12.2 lib/middleman/vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
middleman-0.12.1 lib/middleman/vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
middleman-0.12.0.pre3 lib/middleman/vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
middleman-0.12.0.pre2 lib/middleman/vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
colouringcode-passenger-0.1 vendor/rack-1.0.0-git/lib/rack/builder.rb
middleman-0.12.0.pre lib/middleman/vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
passenger-2.2.7 vendor/rack-1.0.0-git/lib/rack/builder.rb
passenger-2.2.6 vendor/rack-1.0.0-git/lib/rack/builder.rb
middleman-0.10.17 vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
middleman-0.10.16 vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
middleman-0.10.15 vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
rackjour-0.1.8 vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
middleman-0.10.14 vendor/gems/gems/rack-1.0.1/lib/rack/builder.rb
rack-1.0.1 lib/rack/builder.rb
hiraku-rack-1.0.0.1 lib/rack/builder.rb
passenger-2.2.5 vendor/rack-1.0.0-git/lib/rack/builder.rb