added support to cast Float values
This commit is contained in:
parent
9a167cc27d
commit
8f8b5dc568
10
history.txt
10
history.txt
|
@ -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
|
||||
|
||||
* Major enhancements
|
||||
|
|
|
@ -56,7 +56,6 @@ module CouchRest
|
|||
def cast_keys
|
||||
return unless self.class.properties
|
||||
self.class.properties.each do |property|
|
||||
|
||||
next unless property.casted
|
||||
key = self.has_key?(property.name) ? property.name : property.name.to_sym
|
||||
# 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')
|
||||
# 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]
|
||||
# Float instances don't get initialized with #new
|
||||
elsif ((property.init_method == 'new') && target == 'Float')
|
||||
cast_float(self[key])
|
||||
else
|
||||
# Let people use :send as a Time parse arg
|
||||
klass = ::CouchRest.constantize(target)
|
||||
|
@ -84,6 +86,15 @@ module CouchRest
|
|||
end
|
||||
|
||||
end
|
||||
|
||||
def cast_float(value)
|
||||
begin
|
||||
Float(value)
|
||||
rescue
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
|
|
|
@ -141,6 +141,29 @@ describe "ExtendedDocument properties" do
|
|||
@event['occurs_at'].should be_an_instance_of(Time)
|
||||
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
|
||||
|
|
Loading…
Reference in a new issue