Class: Bunch::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/bunch/middleware.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/bunch/middleware.rb', line 7

def initialize(app, options={})
  unless options[:root_url] && options[:path]
    raise "Must provide :root_url and :path"
  end

  @app = app
  @root_url = options.delete(:root_url)
  @endpoint = Bunch::Rack.new(options.delete(:path), options)

  if options[:gzip]
    @endpoint = ::Rack::Deflater.new(@endpoint)
  end
end

Instance Attribute Details

#appObject

Returns the value of attribute app.



5
6
7
# File 'lib/bunch/middleware.rb', line 5

def app
  @app
end

#endpointObject

Returns the value of attribute endpoint.



5
6
7
# File 'lib/bunch/middleware.rb', line 5

def endpoint
  @endpoint
end

Class Method Details

.insert_before(klass, options = {}) ⇒ Object

Binds an instance of Bunch::Middleware in front of any instance of the given middleware class. Whenever klass is instantiated, any calls to klass#call will first pass through the single instance of Middleware created by this method.

You can compose any number of Middleware instances in front of the same class.

In practice, the purpose of this is to allow Bunch to take precedence over Rails::Rack::Static in a Rails 2 context. Since the server's instance of Rails::Rack::Static isn't part of the ActionController stack, it isn't possible to use Rails' normal middleware tools to insert Bunch in front of it, which means any files in public would be served preferentially.

Examples:

if Rails.env.development?
  Bunch::Middleware.insert_before Rails::Rack::Static,
    root_url: '/javascripts', path: 'app/scripts', no_cache: true
end

Parameters:

  • klass (Class)

    Any Rack middleware class.

  • options (Hash) (defaults to: {})

    The options that would normally be passed to Bunch::Middleware#initialize.



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/bunch/middleware.rb', line 71

def insert_before(klass, options={})
  instance = new(nil, options)

  klass.class_eval do
    unbound_call = instance_method(:call)
    define_method(:call) do |env|
      instance.app = unbound_call.bind(self)
      instance.call(env)
    end
  end
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bunch/middleware.rb', line 21

def call(env)
  path = env['PATH_INFO'].to_s
  script_name = env['SCRIPT_NAME'].to_s

  if path =~ root_regexp &&
      (rest = $1) &&
      (rest.empty? || rest[0] == ?/)

    @endpoint.call(
      env.merge(
        'SCRIPT_NAME' => (script_name + @root_url),
        'PATH_INFO'   => rest
      )
    )
  else
    @app.call(env)
  end
end