Permalink
Browse files

Also allow keys with nil values to be accessed as methods on a Hash.

  • Loading branch information...
1 parent 45cd1f6 commit b9bb13dd45c21e59e186a1ed9544294f74455d72 @kevintuhumury kevintuhumury committed Mar 19, 2012
Showing with 45 additions and 7 deletions.
  1. +8 −2 lib/core_ext/hash.rb
  2. +37 −5 spec/core_ext/hash_spec.rb
View
10 lib/core_ext/hash.rb
@@ -1,5 +1,11 @@
class Hash
- def method_missing(key)
- self[key] or self[key.to_s] or super
+ def method_missing(method, *args, &block)
+ if self.has_key? method
+ return self[method]
+ elsif self.has_key? method.to_s
+ return self[method.to_s]
+ else
+ super
+ end
end
end
View
42 spec/core_ext/hash_spec.rb
@@ -5,15 +5,47 @@
context "accessing it's keys as methods" do
let(:hash) do
- { :foo => "bar", "baz" => "qux" }
+ { :foo => "bar", "baz" => "qux", :quux => "", "corge" => "", :grault => nil, "garply" => nil }
end
- it "should get access to the value of a symbol" do
- hash.foo.should eq "bar"
+ context "with the key being a symbol" do
+
+ it "should have a value" do
+ hash.foo.should eq "bar"
+ end
+
+ it "should be empty" do
+ hash.quux.should be_empty
+ end
+
+ it "should be nil" do
+ hash.grault.should be_nil
+ end
+
+ end
+
+ context "with the key being a string" do
+
+ it "should have a value" do
+ hash.baz.should eq "qux"
+ end
+
+ it "should be empty" do
+ hash.corge.should be_empty
+ end
+
+ it "should be nil" do
+ hash.garply.should be_nil
+ end
+
end
- it "should get access to the value of a string" do
- hash.baz.should eq "qux"
+ context "when the key isn't defined" do
+
+ it "should raise a NoMethodError exception" do
+ expect { hash.some_method }.to raise_error NoMethodError
+ end
+
end
end

0 comments on commit b9bb13d

Please sign in to comment.