Rails hash camelize and underscore keys

Camelize hash keys before converting hash to json

Manually using Hash#deep_transform_keys!

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

In jbuilder

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

Snakecase hash keys from json

A: Manually using Hash#deep_transform_keys!

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

B: In middleware

# 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