Camelize JSON keys in Rails
Works well with portrayal, and narrative Rails app design.
Add to your lib/camelize_json_keys.rb
, then require and use as needed.
# USAGE
#
# class MyClass
# include CamelizeJsonKeys.first_letter(:lower) # or :upper
# …
# end
module CamelizeJsonKeys
class << self
def first_letter(first_letter_style)
Module.new {
define_method(:as_json) do |*args, **kwargs|
super(*args, **kwargs).deep_transform_keys { |key|
key.to_s.camelize(first_letter_style)
}
end
}
end
end
end
Code snippets in this post are covered by 0BSD License.