Class: Goliath::Rack::Params

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

Overview

A middle ware to parse params. This will parse both the query string parameters and the body and place them into the params hash of the Goliath::Env for the request.

Examples:

use Goliath::Rack::Params

Instance Method Summary (collapse)

Constructor Details

- (Params) initialize(app)

A new instance of Params



17
18
19
# File 'lib/goliath/rack/params.rb', line 17

def initialize(app)
  @app = app
end

Instance Method Details

- (Object) call(env)



21
22
23
24
25
26
27
28
29
# File 'lib/goliath/rack/params.rb', line 21

def call(env)
  begin
    env['params'] = retrieve_params(env)
  rescue Goliath::Validation::BadRequestError => e
    return validation_error(e.status_code, e.message)
  end

  @app.call(env)
end

- (Object) retrieve_params(env)



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
58
59
60
61
62
63
# File 'lib/goliath/rack/params.rb', line 31

def retrieve_params(env)
  params = {}
  params.merge!(::Rack::Utils.parse_nested_query(env['QUERY_STRING']))

  if env['rack.input']
    post_params = ::Rack::Utils::Multipart.parse_multipart(env)
    unless post_params
      body = env['rack.input'].read
      env['rack.input'].rewind

      unless body.empty?
        begin
          post_params = case(env['CONTENT_TYPE'])
          when URL_ENCODED then
            ::Rack::Utils.parse_nested_query(body)
          when JSON_ENCODED then
            MultiJson.decode(body)
          else
            {}
          end
        rescue StandardError => e
          raise Goliath::Validation::BadRequestError, "Invalid parameters: #{e.class.to_s}"
        end
      else
        post_params = {}
      end
    end

    params.merge!(post_params)
  end

  params
end