Class: Rack::ParamsKeyConverter

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ ParamsKeyConverter

Returns a new instance of ParamsKeyConverter.



6
7
8
# File 'lib/rack/params_key_converter.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rack/params_key_converter.rb', line 10

def call(env)
  # GET
  env["action_dispatch.request.query_parameters"] = convert_key(:underscore, env["action_dispatch.request.query_parameters"])
  # POST
  env["rack.request.form_hash"] = convert_key(:underscore, env["rack.request.form_hash"])
  # JSON
  env["action_dispatch.request.request_parameters"] = convert_key(:underscore, env["action_dispatch.request.request_parameters"])

  status, headers, body = @app.call(env)

  str = body.shift
  h = JSON.parse(str)
  body = [convert_key(:camelize, h).to_json]

  [status, headers, body]
end

#convert_key(strategy, hash) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rack/params_key_converter.rb', line 27

def convert_key(strategy, hash)
  return hash if hash.blank?
  return hash unless [Hash, Array].include?(hash.class)
  converted_hash = {}

  hash.each do |k, v|
    k = k.to_s
    case v
    when Array
      converted_hash[make_key(k, strategy)] = v.grep(Hash) { |x| convert_key(strategy, x) }
    when Hash
      converted_hash[make_key(k, strategy)] = convert_key(strategy, v)
    else
      converted_hash[make_key(k, strategy)] = v
    end
  end

  converted_hash
end

#make_key(k, strategy) ⇒ Object



47
48
49
50
51
52
# File 'lib/rack/params_key_converter.rb', line 47

def make_key(k, strategy)
  if strategy == :camelize
    return k.send(strategy, :lower)
  end
  k.send(strategy)
end