Skip to content

Instantly share code, notes, and snippets.

@jasonwbarnett
Forked from timruffles/hash_converter.rb
Created January 31, 2015 07:21
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 jasonwbarnett/0ecdd96ef7b91e9d31c6 to your computer and use it in GitHub Desktop.
Save jasonwbarnett/0ecdd96ef7b91e9d31c6 to your computer and use it in GitHub Desktop.
module HashConverter
class << self
def to_underscore hash
convert hash, :underscore
end
def to_camel_case hash
convert hash, :camelize
end
def convert obj, *method
case obj
when Hash
obj.inject({}) do |h,(k,v)|
v = convert v, *method
h[k.send(*method)] = v
h
end
when Array
obj.map {|m| convert m, *method }
else
obj
end
end
end
end
puts HashConverter.to_underscore({ "helloILikeThis" => { "recursesThrough" => [{"evenInto" => "arraysButNotVals"}] }})
puts HashConverter.to_camel_case({"hello_i_like_this"=>{"recurses_through"=>[{"even_into"=>"arrays_but_not_vals"}]}})
puts HashConverter.to_camel_case HashConverter.to_underscore({ "helloILikeThis" => { "recursesThrough" => [{"evenInto" => "arraysButNotVals"}] }})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment