Added code to generate a property? method for properties casted as :boolean

Signed-off-by: Matt Aimonetti <mattaimonetti@gmail.com>
This commit is contained in:
John Wood 2009-07-25 11:12:03 +08:00 committed by Matt Aimonetti
parent a8c7256974
commit d1d8da513c
2 changed files with 42 additions and 1 deletions

View file

@ -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}

View file

@ -161,7 +161,33 @@ 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