Skip to content

Instantly share code, notes, and snippets.

@kimh
Created February 21, 2015 10:42
Show Gist options
  • Select an option

  • Save kimh/4c6fbe42f4d0e2e65bd3 to your computer and use it in GitHub Desktop.

Select an option

Save kimh/4c6fbe42f4d0e2e65bd3 to your computer and use it in GitHub Desktop.
Convert hash keys to camel case deeply
require "minitest/autorun"
require "json"
require "active_support/inflector"
def to_camel(data)
# Do nothing when data is neither Hash or Array.
# This is the guard for array data which mixes non different class.
return data unless data.respond_to?(:inject)
data.inject({}) do |h,(k,v)|
if v.kind_of? Hash
v = to_camel(v)
end
if v.kind_of? Array
v = v.map {|a| to_camel(a)}
end
h[k.camelize(:lower)] = v; h
end
end
describe "to_camel" do
let(:flat_hash) {
{
"my_name" => "Kim Hirokuni",
"age" => 31
}
}
let(:nested_hash) {
{
"my_name" => "Kim Hirokuni",
"physical_feature" => {
"color_of_eye" => "black"
},
"job_history" => {
"kvh" => {
"job_title" => "enginner"
}
}
}
}
let(:nested_array) {
{
"my_name" => "Kim Hirokuni",
"pets_history" => [
{"pet_name" => "eru"},
{"pet_name" => "leo"},
"string"
]
}
}
let(:string) {
"string"
}
it "converts flat hash" do
assert_equal({"myName" => "Kim Hirokuni", "age" => 31}, to_camel(flat_hash))
end
it "converts nested hash" do
assert_equal(
{"myName" => "Kim Hirokuni", "physicalFeature" => {"colorOfEye" => "black"}, "jobHistory" => {"kvh" => {"jobTitle"=> "enginner"}}},
to_camel(nested_hash)
)
end
it "converts nested hash in array" do
assert_equal({"myName" => "Kim Hirokuni", "petsHistory" => [{"petName" => "eru"}, {"petName" => "leo"}, "string"]}, to_camel(nested_array))
end
it 'does nothing when passing object that doesn not implement #inject' do
assert_equal("string", to_camel(string))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment