Skip to content

Instantly share code, notes, and snippets.

@redconfetti
Created October 21, 2014 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redconfetti/155ed2309ddbea52fd7d to your computer and use it in GitHub Desktop.
Save redconfetti/155ed2309ddbea52fd7d to your computer and use it in GitHub Desktop.
Camelize Keys
// Taken from https://github.com/rails-api/active_model_serializers/issues/398#issuecomment-26072287
class Hash
def camelize_keys!
update_keys!(:camelize, :lower)
end
def underscore_keys!
update_keys!(:underscore)
end
def update_keys!(method, *args)
self.keys.each do |key|
updated_key = key.to_s.send(method, *args).to_sym
self[updated_key] = self.delete(key)
self[updated_key].update_keys!(method, *args) if self[updated_key].kind_of? Hash
end
self
end
end
# Example in Rails environment:
#
# >> nested_hash = { :this_is_cool => '123', :so_is_this => { :level_two => 2, :oh_yeah => 'oh yeah', :another_level => {:level_three => 3, :okay_thats_enough => 'yeah, enough man'} }, 'really_cool' => [{:totally_cool => 'totally'}] }
# => {:this_is_cool=>"123", :so_is_this=>{:level_two=>2, :oh_yeah=>"oh yeah", :another_level=>{:level_three=>3, :okay_thats_enough=>"yeah, enough man"}}, "really_cool"=>[{:totally_cool=>"totally"}]}
# >> nested_hash.camelize_keys!
# => {:thisIsCool=>"123", :soIsThis=>{:levelTwo=>2, :ohYeah=>"oh yeah", :anotherLevel=>{:levelThree=>3, :okayThatsEnough=>"yeah, enough man"}}, :reallyCool=>[{:totally_cool=>"totally"}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment