Class: Muster::Rack

Inherits:
Object
  • Object
show all
Defined in:
lib/muster/rack.rb

Overview

Rack middleware plugin for Muster query string parsing

Examples:


app = Rack::Builder.new do
  use Muster::Rack, Muster::Strategies::Hash, :fields => [:name, :choices]
end

# GET /?name=bob&choices=1&choices=2
match '/' do
  env['muster.query']  #=> {'name' => 'bob', 'choices' => ['1', '2']}
end

Constant Summary collapse

QUERY =

Key in ENV where processed query string are stored

'muster.query'.freeze
QUERY_STRING =

Key in ENV where the query string that was processed is stored

'muster.query_string'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, strategy, options = {}) ⇒ Rack

Creates a new Rack::Muster middleware instance

Examples:


middleware = Muster::Rack.new(app, Muster::Strategies::Hash, :fields => [:name, :choices])

strategy = Muster::Strategies::Hash.new(:fields => [:name, :choices])
middleware = Muster::Rack.new(app, strategy)

Parameters:

  • app (String)

    Rack application

  • strategy (Muster::Strategies::Rack)

    Muster query string parsing strategy to run

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

    options to pass to the specified strategy



50
51
52
53
54
# File 'lib/muster/rack.rb', line 50

def initialize( app, strategy, options={} )
  @app = app
  @strategy = strategy
  @options = options
end

Instance Attribute Details

#appObject (readonly)

Returns Rack application middleware is running under.

Returns:

  • (Object)

    Rack application middleware is running under



22
23
24
# File 'lib/muster/rack.rb', line 22

def app
  @app
end

#optionsHash (readonly)

Returns options to pass to strategy.

Returns:

  • (Hash)

    options to pass to strategy



30
31
32
# File 'lib/muster/rack.rb', line 30

def options
  @options
end

#strategyMuster::Strategies::Rack (readonly)

Returns Muster Strategy to run.

Returns:



26
27
28
# File 'lib/muster/rack.rb', line 26

def strategy
  @strategy
end

Instance Method Details

#call(env) ⇒ Array

Handle Rack request

Parameters:

  • env (Hash)

    Rack environment

Returns:

  • (Array)


61
62
63
64
65
66
67
68
69
70
# File 'lib/muster/rack.rb', line 61

def call( env )
  request  = ::Rack::Request.new(env)
  parser   = self.strategy.kind_of?(Class) ? self.strategy.new(options) : self.strategy

  env[QUERY] ||= Muster::Results.new({})
  env[QUERY].merge! parser.parse(request.query_string)
  env[QUERY_STRING] = request.query_string

  @app.call(env)
end