From 651a0bd00bb8c6ce620776022e787aaa6518769f Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Sat, 16 Oct 2010 13:35:37 +0200 Subject: [PATCH] Don't raise a NoMethod error for attributes with a falsy value. Fixes a problem with the Attributes mixin where an attribute set with a falsy value such as false or nil, the model would not respond to the attribute reader. --- README.md | 3 ++- lib/broach/attributes.rb | 4 ++-- test/unit/attributes_test.rb | 23 +++++++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 test/unit/attributes_test.rb diff --git a/README.md b/README.md index ab98757..480433d 100644 --- a/README.md +++ b/README.md @@ -31,4 +31,5 @@ The easiest way to install Broach and its dependencies is to install the gem. Eloy Duran Ilya Sabanin -Todd Eichel \ No newline at end of file +Todd Eichel +Anton Mironov \ No newline at end of file diff --git a/lib/broach/attributes.rb b/lib/broach/attributes.rb index e1808cb..3f55a56 100644 --- a/lib/broach/attributes.rb +++ b/lib/broach/attributes.rb @@ -8,8 +8,8 @@ def initialize(attributes) def id; @attributes['id']; end def method_missing(method, *arguments, &block) - if value = @attributes[method.to_s] - value + if key = method.to_s and @attributes.has_key?(key) + @attributes[key] else super end diff --git a/test/unit/attributes_test.rb b/test/unit/attributes_test.rb new file mode 100644 index 0000000..e02d1a0 --- /dev/null +++ b/test/unit/attributes_test.rb @@ -0,0 +1,23 @@ +require File.expand_path('../../start', __FILE__) + +class Mole + include Broach::Attributes +end + +describe "A class with Attributes" do + before do + @mole = Mole.new('name' => "Jerry", 'glasses' => false, 'description' => nil) + end + + it "returns it's attribute through accessor methods" do + @mole.name.should == "Jerry" + @mole.glasses.should.be.false + @mole.description.should.be.nil + end + + it "does not respond to methods for attributes which haven't been set" do + lambda { + @mole.unknown + }.should.raise(NoMethodError) + end +end \ No newline at end of file