Class: Evrone::Common::Rack::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/evrone/common/rack/builder.rb,
lib/evrone/common/rack/builder/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_app = nil, &block) ⇒ Builder

Returns a new instance of Builder.



8
9
10
11
# File 'lib/evrone/common/rack/builder.rb', line 8

def initialize(default_app = nil,&block)
  @use, @map, @run = [], nil, default_app
  instance_eval(&block) if block_given?
end

Class Method Details

.app(default_app = nil, &block) ⇒ Object



13
14
15
# File 'lib/evrone/common/rack/builder.rb', line 13

def self.app(default_app = nil, &block)
  self.new(default_app, &block).to_app
end

Instance Method Details

#call(env) ⇒ Object



50
51
52
# File 'lib/evrone/common/rack/builder.rb', line 50

def call(env)
  to_app.call(env)
end

#to_app(app) ⇒ Object



44
45
46
47
48
# File 'lib/evrone/common/rack/builder.rb', line 44

def to_app(app)
  app ||= @run
  fail "missing run or map statement" unless app
  @use.reverse.inject(app) { |a,e| e[a] }
end

#use(middleware, *args, &block) ⇒ Object

Specifies middleware to use in a stack.

class Middleware
  def initialize(app)
    @app = app
  end

  def call(env)
    env["rack.some_header"] = "setting an example"
    @app.call(env)
  end
end

use Middleware
run lambda { |env| [200, { "Content-Type => "text/plain" }, ["OK"]] }

All requests through to this application will first be processed by the middleware class. The call method in this example sets an additional environment key which then can be referenced in the application if required.



36
37
38
39
40
41
42
# File 'lib/evrone/common/rack/builder.rb', line 36

def use(middleware, *args, &block)
  if @map
    mapping, @map = @map, nil
    @use << proc { |app| generate_map app, mapping }
  end
  @use << proc { |app| middleware.new(app, *args, &block) }
end