Class: Committee::RequestUnpacker

Inherits:
Object
  • Object
show all
Defined in:
lib/committee/request_unpacker.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RequestUnpacker

Returns a new instance of RequestUnpacker.



23
24
25
26
27
28
# File 'lib/committee/request_unpacker.rb', line 23

def initialize(options={})
  @allow_form_params  = options[:allow_form_params]
  @allow_get_body     = options[:allow_get_body]
  @allow_query_params = options[:allow_query_params]
  @optimistic_json    = options[:optimistic_json]
end

Class Method Details

.indifferent_params(object) ⇒ Object

Enable string or symbol key access to the nested params hash.

(Copied from Sinatra)



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/committee/request_unpacker.rb', line 9

def indifferent_params(object)
  case object
  when Hash
    new_hash = Committee::Utils.indifferent_hash
    object.each { |key, value| new_hash[key] = indifferent_params(value) }
    new_hash
  when Array
    object.map { |item| indifferent_params(item) }
  else
    object
  end
end

Instance Method Details

#unpack_headers(request) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/committee/request_unpacker.rb', line 59

def unpack_headers(request)
  env = request.env
  base = env.keys.grep(/HTTP_/).inject({}) do |headers, key|
    headerized_key = key.gsub(/^HTTP_/, '').gsub(/_/, '-')
    headers[headerized_key] = env[key]
    headers
  end

  base['Content-Type'] = env['CONTENT_TYPE'] if env['CONTENT_TYPE']
  base
end

#unpack_query_params(request) ⇒ Object



55
56
57
# File 'lib/committee/request_unpacker.rb', line 55

def unpack_query_params(request)
  @allow_query_params ? self.class.indifferent_params(request.GET) : {}
end

#unpack_request_params(request) ⇒ Object

return params and is_form_params



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/committee/request_unpacker.rb', line 31

def unpack_request_params(request)
  # if Content-Type is empty or JSON, and there was a request body, try to
  # interpret it as JSON
  params = if !request.media_type || request.media_type =~ %r{application/(?:.*\+)?json}
    parse_json(request)
  elsif @optimistic_json
    begin
      parse_json(request)
    rescue JSON::ParserError
      nil
    end
  end

  return [params, false] if params

  if @allow_form_params && %w[application/x-www-form-urlencoded multipart/form-data].include?(request.media_type)
    # Actually, POST means anything in the request body, could be from
    # PUT or PATCH too. Silly Rack.
    return [request.POST, true] if request.POST
  end

  [{}, false]
end