Created
November 30, 2015 16:36
-
-
Save jazzytomato/a059d1e118a87c99dddd to your computer and use it in GitHub Desktop.
A helper for JSON interaction. Treat the hashes recursively
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
module Utilities | |
# A helper for JSON interaction. Treat the hashes recursively | |
module CamelSnakeHash | |
# camelize and stringify keys | |
def camelize_keys(value) | |
case value | |
when Array | |
value.map { |v| camelize_keys(v) } | |
when Hash | |
Hash[value.map { |k, v| [k.to_s.camelize(:upper), camelize_keys(v)] }] | |
else | |
value | |
end | |
end | |
# underscore and symbolize keys | |
def underscore_keys(value) | |
case value | |
when Array | |
value.map { |v| underscore_keys(v) } | |
when Hash | |
Hash[value.map { |k, v| [k.to_s.underscore.to_sym, underscore_keys(v)] }] | |
else | |
value | |
end | |
end | |
end | |
end | |
module Utilities | |
describe CamelSnakeHash do | |
include CamelSnakeHash | |
let(:snake_hash) do | |
{ array_of_hashes: [{ an_integer: 1, a_string: 'bonjour' }, { a_hash: { stuff: 'stuff' } }], stuff: 'stuff' } | |
end | |
let(:camel_hash) do | |
{ 'ArrayOfHashes' => [{ 'AnInteger' => 1, 'AString' => 'bonjour' }, { 'AHash' => { 'Stuff' => 'stuff' } }], 'Stuff' => 'stuff' } | |
end | |
it 'should camelize and stringify keys' do | |
expect(camelize_keys(snake_hash)).to eq(camel_hash) | |
end | |
it 'should underscore and symbolize keys' do | |
expect(underscore_keys(camel_hash)).to eq(snake_hash) | |
end | |
it 'should produce the same hash' do | |
expect(camelize_keys(underscore_keys(camel_hash))).to eq(camel_hash) | |
expect(underscore_keys(camelize_keys(snake_hash))).to eq(snake_hash) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment