Created
October 21, 2014 16:59
-
-
Save redconfetti/155ed2309ddbea52fd7d to your computer and use it in GitHub Desktop.
Camelize Keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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