Created
March 6, 2013 11:00
-
-
Save henrik/5098550 to your computer and use it in GitHub Desktop.
Recursive closed struct.
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
class RecursiveClosedStruct | |
def initialize(hash) | |
@hash = hash | |
end | |
def method_missing(name, *) | |
value = fetch(name) | |
if value.is_a?(Hash) | |
self.class.new(value) | |
else | |
value | |
end | |
end | |
private | |
def fetch(name) | |
@hash.fetch(name) do | |
raise NoMethodError.new("undefined method `#{name}' for #{self}") | |
end | |
end | |
end |
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" | |
require "minitest/pride" | |
require "recursive_closed_struct" | |
describe RecursiveClosedStruct do | |
it "provides readers from a hash" do | |
subject = RecursiveClosedStruct.new(key: "value") | |
assert_equal "value", subject.key | |
end | |
it "raises when there's no such key" do | |
subject = RecursiveClosedStruct.new(key: "value") | |
assert_raises(NoMethodError) do | |
subject.other_key | |
end | |
end | |
it "recurses through hashes" do | |
subject = RecursiveClosedStruct.new({ | |
one: { two: { three: "four" } } | |
}) | |
assert_equal "four", subject.one.two.three | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: currently assumes hash has symbol keys.