Skip to content

Instantly share code, notes, and snippets.

@henrik
Created March 6, 2013 11:00
Show Gist options
  • Save henrik/5098550 to your computer and use it in GitHub Desktop.
Save henrik/5098550 to your computer and use it in GitHub Desktop.
Recursive closed struct.
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
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
@henrik
Copy link
Author

henrik commented Nov 19, 2013

Note: currently assumes hash has symbol keys.

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