Rails Hash - camelize and underscore keys

November 29, 2019

rubyrailshashjsonapi

Using Hash#deeptransformkeys!

# Convert keys to the lower camel case.
hash.deep_transform_keys! { |key| key.camelize(:lower) }
# Convert keys to the underscore case.
hash.deep_transform_keys! { |key| key.underscore }

Automatically converting for outgoing JSON response in jbuilder

# config/environment.rb
Jbuilder.key_format camelize: :lower

Automatically converting keys for incoming request params in middleware

  • Automatically snakecase the keys of any incoming params.
# application.rb
require_relative "../app/middlewares/snake_case_parameters"
config.middleware.use SnakeCaseParameters
# app/middlewares/snake_case_parameters.rb
# A middleware that underscores the keys of any incoming (to the rails server) params.
class SnakeCaseParameters
  def initialize(app)
    @app = app
  end

  def call(env)
    request = ActionDispatch::Request.new(env)
    request.request_parameters.deep_transform_keys!(&:underscore)
    request.query_parameters.deep_transform_keys!(&:underscore)

    @app.call(env)
  end
end

Additional resources