Last active
December 24, 2015 20:19
-
-
Save philosodad/6856705 to your computer and use it in GitHub Desktop.
Monkey patch of the Hash class to convert all string keys to symbols at arbritray depth
This file contains 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
require "minitest/autorun" | |
class Hash | |
def symogriform | |
symogriformed = {} | |
symogrified = self | |
symogrified.keys.each do |key| | |
if symogrified[key].is_a?(Hash) | |
symogrified[key] = symogrified[key].symogriform | |
end | |
end | |
symogriformed.merge!(symogrify(symogrified)) | |
symogriformed | |
end | |
def symogrify part | |
part.keys.inject({}){|hash, key| hash.merge({symog(key) => part[key]})} | |
end | |
def symog key | |
key.is_a?(String) ? key.to_sym : key | |
end | |
end | |
describe Hash do | |
describe "symogriform" do | |
it "should convert keys to symbols" do | |
{"A" => :a, "B" => :b}.symogriform.must_equal({A: :a, B: :b}) | |
end | |
it "should convert keys at arbitrary layers to symbols" do | |
{"A" => {"A" => "a"}, "B" => {"B" => {"C" => {}}}}.symogriform.must_equal({A: {A: "a"}, B: {B: {C: {}}}}) | |
end | |
it "should not error out with non-string keys" do | |
{1 => "a", 2 => "a"}.symogriform.must_equal({1 => "a", 2 => "a"}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment