Skip to content

Instantly share code, notes, and snippets.

@morhekil
Last active January 22, 2017 22:12
Show Gist options
  • Save morhekil/998709 to your computer and use it in GitHub Desktop.
Save morhekil/998709 to your computer and use it in GitHub Desktop.
Implementation of deep symbolization of keys for Ruby hashes
# Symbolizes all of hash's keys and subkeys.
# Also allows for custom pre-processing of keys (e.g. downcasing, etc)
# if the block is given:
#
# somehash.deep_symbolize { |key| key.downcase }
#
# Usage: either include it into global Hash class to make it available to
# to all hashes, or extend only your own hash objects with this
# module.
# E.g.:
# 1) class Hash; include DeepSymbolizable; end
# 2) myhash.extend DeepSymbolizable
module DeepSymbolizable
def deep_symbolize(&block)
method = self.class.to_s.downcase.to_sym
syms = DeepSymbolizable::Symbolizers
syms.respond_to?(method) ? syms.send(method, self, &block) : self
end
module Symbolizers
extend self
# the primary method - symbolizes keys of the given hash,
# preprocessing them with a block if one was given, and recursively
# going into all nested enumerables
def hash(hash, &block)
hash.inject({}) do |result, (key, value)|
# Recursively deep-symbolize subhashes
value = _recurse_(value, &block)
# Pre-process the key with a block if it was given
key = yield key if block_given?
# Symbolize the key string if it responds to to_sym
sym_key = key.to_sym rescue key
# write it back into the result and return the updated hash
result[sym_key] = value
result
end
end
# walking over arrays and symbolizing all nested elements
def array(ary, &block)
ary.map { |v| _recurse_(v, &block) }
end
# handling recursion - any Enumerable elements (except String)
# is being extended with the module, and then symbolized
def _recurse_(value, &block)
if value.is_a?(Enumerable) && !value.is_a?(String)
# support for a use case without extended core Hash
value.extend DeepSymbolizable unless value.class.include?(DeepSymbolizable)
value = value.deep_symbolize(&block)
end
value
end
end
end
require 'rspec'
require 'deep_symbolize'
describe 'Hash#deep_symbolize' do
let(:hash) {{}}
subject do
hash.extend DeepSymbolizable
hash.deep_symbolize
end
context 'on simple hash' do
let(:hash) {{ :key1 => 'val1', 'key2' => 'val2' }}
it { should == { :key1 => 'val1', :key2 => 'val2' } }
end
context 'on nested hash' do
let(:hash) {{ 'key1' => 'val1', 'subkey' => { 'key2' => 'val2' } }}
it { should == { :key1 => 'val1', :subkey => { :key2 => 'val2' } } }
end
context 'on a hash with nested array' do
let(:hash) {{ 'key1' => 'val1', 'subkey' => [{ 'key2' => 'val2' }] }}
it { should == { :key1 => 'val1', :subkey => [{ :key2 => 'val2' }] } }
end
describe 'preprocessing keys' do
subject do
hash.extend DeepSymbolizable
hash.deep_symbolize { |k| k.upcase }
end
let(:hash) {{ 'key1' => 'val1', 'subkey' => [{ 'key2' => 'val2' }] }}
it { should == { :KEY1 => 'val1', :SUBKEY => [{ :KEY2 => 'val2' }] } }
end
end
The MIT License (MIT)
Copyright (c) 2015 Oleg Ivanov http://github.com/morhekil
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@artemk
Copy link

artemk commented Mar 14, 2012

this does not work for {'a' => [{'b'=> 't'}]}

@morhekil
Copy link
Author

you're right, it didn't. Never really intended it to, but if you need something more complex - here's a touch more involved version, that goes down into arrays as well, and can be easily extended to walk over any other types you need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment