Created
June 6, 2013 08:40
-
-
Save IanVaughan/5720166 to your computer and use it in GitHub Desktop.
Very basic way to access ruby hashes via method name.
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
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 |
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
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