From d1d8da513c9a5e8782455ab7516291a45e3e4a7e Mon Sep 17 00:00:00 2001 From: John Wood Date: Sat, 25 Jul 2009 11:12:03 +0800 Subject: [PATCH] Added code to generate a property? method for properties casted as :boolean Signed-off-by: Matt Aimonetti --- lib/couchrest/mixins/properties.rb | 15 +++++++++++++++ spec/couchrest/more/property_spec.rb | 28 +++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/lib/couchrest/mixins/properties.rb b/lib/couchrest/mixins/properties.rb index 2982d30..69c9411 100644 --- a/lib/couchrest/mixins/properties.rb +++ b/lib/couchrest/mixins/properties.rb @@ -77,6 +77,9 @@ module CouchRest # Float instances don't get initialized with #new elsif ((property.init_method == 'new') && target == 'Float') cast_float(self[key]) + # 'boolean' type is simply used to generate a property? accessor method + elsif ((property.init_method == 'new') && target == 'boolean') + self[key] else # Let people use :send as a Time parse arg klass = ::CouchRest.constantize(target) @@ -128,6 +131,18 @@ module CouchRest end EOS + if property.type == 'boolean' + class_eval <<-EOS, __FILE__, __LINE__ + def #{property.name}? + if self['#{property.name}'].nil? || self['#{property.name}'] == false || self['#{property.name}'].to_s.downcase == 'false' + false + else + true + end + end + EOS + end + if property.alias class_eval <<-EOS, __FILE__, __LINE__ alias #{property.alias.to_sym} #{property.name.to_sym} diff --git a/spec/couchrest/more/property_spec.rb b/spec/couchrest/more/property_spec.rb index 6782789..efeba94 100644 --- a/spec/couchrest/more/property_spec.rb +++ b/spec/couchrest/more/property_spec.rb @@ -161,9 +161,35 @@ describe "ExtendedDocument properties" do it "should work fine when a float is being passed" do RootBeerFloat.new(:price => 9.99).price.should == 9.99 end - end + describe "casting to a boolean value" do + class RootBeerFloat < CouchRest::ExtendedDocument + use_database DB + property :tasty, :cast_as => :boolean + end + + it "should add an accessor with a '?' for boolean attributes that returns true or false" do + RootBeerFloat.new(:tasty => true).tasty?.should == true + RootBeerFloat.new(:tasty => 'you bet').tasty?.should == true + RootBeerFloat.new(:tasty => 123).tasty?.should == true + + RootBeerFloat.new(:tasty => false).tasty?.should == false + RootBeerFloat.new(:tasty => 'false').tasty?.should == false + RootBeerFloat.new(:tasty => 'FaLsE').tasty?.should == false + RootBeerFloat.new(:tasty => nil).tasty?.should == false + end + + it "should return the real value when the default accessor is used" do + RootBeerFloat.new(:tasty => true).tasty.should == true + RootBeerFloat.new(:tasty => 'you bet').tasty.should == 'you bet' + RootBeerFloat.new(:tasty => 123).tasty.should == 123 + RootBeerFloat.new(:tasty => 'false').tasty.should == 'false' + RootBeerFloat.new(:tasty => false).tasty.should == false + RootBeerFloat.new(:tasty => nil).tasty.should == nil + end + end + end end