Skip to content

Instantly share code, notes, and snippets.

@dbi
Created November 20, 2012 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbi/4116854 to your computer and use it in GitHub Desktop.
Save dbi/4116854 to your computer and use it in GitHub Desktop.
Make a hash with keys callable as methods
class DeepStruct
attr_reader :hash
def initialize(hash)
@hash = hash.with_indifferent_access
end
def method_missing(method, *args, &block)
if hash.key?(method)
value = hash[method]
if value.kind_of? Hash
self.class.new(value)
else
value
end
else
super
end
end
end
require_relative "deep_struct"
require "active_support/hash_with_indifferent_access"
require "active_support/core_ext/hash/indifferent_access"
describe DeepStruct do
context "with string keys" do
let(:hash) do
DeepStruct.new({"a" => 1, "b" => 2, "c" => {"d" => 3}})
end
it "access keys directly" do
hash.b.should eq(2)
end
it "access nested keys" do
hash.c.d.should eq(3)
end
end
context "with symbol keys" do
let(:hash) do
DeepStruct.new({a: 1, b: 2, c: {d: 3}})
end
it "access keys directly" do
hash.b.should eq(2)
end
it "access nested keys" do
hash.c.d.should eq(3)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment