Last active
August 29, 2015 14:00
-
-
Save jbpros/11354944 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HashStyles | |
def underscore_hash_keys(value) | |
case value | |
when Array | |
value.map { |v| underscore_hash_keys(v) } | |
when Hash | |
Hash[value.map { |k, v| [underscore_key(k), underscore_hash_keys(v)] }] | |
else | |
value | |
end | |
end | |
def camelize_hash_keys(value) | |
case value | |
when Array | |
value.map { |v| camelize_hash_keys(v) } | |
when Hash | |
Hash[value.map { |k, v| [camelize_key(k), camelize_hash_keys(v)] }] | |
else | |
value | |
end | |
end | |
def underscore_key(k) | |
k.to_s.underscore | |
end | |
def camelize_key(k) | |
k.to_s.camelize :lower | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ParamsStyler | |
include HashStyles | |
JSON_MEDIA_TYPE = /^application\/json/ | |
def initialize app | |
@app = app | |
end | |
def call env | |
if applicable_to_env?(env) && json_media_type?(env['CONTENT_TYPE']) | |
env['action_dispatch.request.request_parameters'] = underscore_hash_keys env['action_dispatch.request.request_parameters'] | |
end | |
status, headers, response = @app.call env | |
if applicable_to_env?(env) && json_media_type?(headers['Content-Type']) | |
response.body = camelize_hash_keys(JSON.parse(response.body)).to_json | |
end | |
[status, headers, response] | |
end | |
def applicable_to_env? env | |
env['PATH_INFO'].match /\A\/api\/.*/ | |
end | |
def json_media_type? media_type | |
media_type =~ JSON_MEDIA_TYPE | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment