[Rails] Camelize and underscore Hash/JSON keys

While the snake case Hash keys are conventionally used in Ruby world, sometimes we prefer camel case keys in the front end. Here is my note on how to handle this problem.

Camelizing keys of outgoing JSON data

A: using Hash#deep_transform_keys!

hash.deep_transform_keys! { |key| key.camelize(:lower) }

B: using jbuilder

  • Automatically camelize the keys of any outgoing JSON data.
# config/environment.rb
Jbuilder.key_format camelize: :lower

Snakecasing keys of incoming JSON data

A: using Hash#deep_transform_keys!

hash.deep_transform_keys! { |key| key.underscore }

B: in a custom 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

Resources