Skip to content

Instantly share code, notes, and snippets.

@regedarek
Forked from IanVaughan/hash_accessor.rb
Created June 19, 2013 10:47
Show Gist options
  • Save regedarek/5813420 to your computer and use it in GitHub Desktop.
Save regedarek/5813420 to your computer and use it in GitHub Desktop.
module HashAccessor
def method_missing(name, *args, &block)
h = Hash[self.map{|(k,v)| [k.to_sym,v]}]
if h.has_key?(name.to_sym)
h[name.to_sym]
end
end
end
describe HashAccessor do
class Hash
include HashAccessor
end
context "hash symbol keys" do
subject { {a: 1, b: 2} }
its(:a) { should == 1 }
its(:b) { should == 2 }
its(:c) { should be_nil }
its('a') { should == 1 }
its('b') { should == 2 }
its('c') { should be_nil }
end
context "hash string keys" do
subject { {'a' => 1, 'b' => 2} }
its(:a) { should == 1 }
its(:b) { should == 2 }
its(:c) { should be_nil }
its('a') { should == 1 }
its('b') { should == 2 }
its('c') { should be_nil }
end
context "empty hash" do
subject { {} }
its(:a) { should be_nil }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment