added support to cast Float values

This commit is contained in:
Matt Aimonetti 2009-07-16 19:52:53 -07:00
parent 9a167cc27d
commit 8f8b5dc568
3 changed files with 45 additions and 1 deletions

View file

@ -1,3 +1,13 @@
== 0.31
* Major enhancements
* Created an abstraction HTTP layer to support different http adapters (Matt Aimonetti)
* Minor enhancements
* Added Float casting (Ryan Felton & Matt Aimonetti)
== 0.30 == 0.30
* Major enhancements * Major enhancements

View file

@ -56,7 +56,6 @@ module CouchRest
def cast_keys def cast_keys
return unless self.class.properties return unless self.class.properties
self.class.properties.each do |property| self.class.properties.each do |property|
next unless property.casted next unless property.casted
key = self.has_key?(property.name) ? property.name : property.name.to_sym key = self.has_key?(property.name) ? property.name : property.name.to_sym
# Don't cast the property unless it has a value # Don't cast the property unless it has a value
@ -75,6 +74,9 @@ module CouchRest
self[property.name] = if ((property.init_method == 'new') && target == 'Time') self[property.name] = if ((property.init_method == 'new') && target == 'Time')
# Using custom time parsing method because Ruby's default method is toooo slow # Using custom time parsing method because Ruby's default method is toooo slow
self[key].is_a?(String) ? Time.mktime_with_offset(self[key].dup) : self[key] self[key].is_a?(String) ? Time.mktime_with_offset(self[key].dup) : self[key]
# Float instances don't get initialized with #new
elsif ((property.init_method == 'new') && target == 'Float')
cast_float(self[key])
else else
# Let people use :send as a Time parse arg # Let people use :send as a Time parse arg
klass = ::CouchRest.constantize(target) klass = ::CouchRest.constantize(target)
@ -84,6 +86,15 @@ module CouchRest
end end
end end
def cast_float(value)
begin
Float(value)
rescue
value
end
end
end end
module ClassMethods module ClassMethods

View file

@ -141,6 +141,29 @@ describe "ExtendedDocument properties" do
@event['occurs_at'].should be_an_instance_of(Time) @event['occurs_at'].should be_an_instance_of(Time)
end end
end end
describe "casting to Float object" do
class RootBeerFloat < CouchRest::ExtendedDocument
use_database DB
property :price, :cast_as => 'Float'
end
it "should convert a string into a float if casted as so" do
RootBeerFloat.new(:price => '12.50').price.should == 12.50
RootBeerFloat.new(:price => '9').price.should == 9.0
RootBeerFloat.new(:price => '-9').price.should == -9.0
end
it "should not convert a string if it's not a string that can be cast as a float" do
RootBeerFloat.new(:price => 'test').price.should == 'test'
end
it "should work fine when a float is being passed" do
RootBeerFloat.new(:price => 9.99).price.should == 9.99
end
end
end end
end end