From 8f8b5dc568a9886725053fd95bbb5ade2f6eab9b Mon Sep 17 00:00:00 2001 From: Matt Aimonetti Date: Thu, 16 Jul 2009 19:52:53 -0700 Subject: [PATCH] added support to cast Float values --- history.txt | 10 ++++++++++ lib/couchrest/mixins/properties.rb | 13 ++++++++++++- spec/couchrest/more/property_spec.rb | 23 +++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/history.txt b/history.txt index a8db62f..0035981 100644 --- a/history.txt +++ b/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 diff --git a/lib/couchrest/mixins/properties.rb b/lib/couchrest/mixins/properties.rb index 19479e3..2982d30 100644 --- a/lib/couchrest/mixins/properties.rb +++ b/lib/couchrest/mixins/properties.rb @@ -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 diff --git a/spec/couchrest/more/property_spec.rb b/spec/couchrest/more/property_spec.rb index 8559c8f..6782789 100644 --- a/spec/couchrest/more/property_spec.rb +++ b/spec/couchrest/more/property_spec.rb @@ -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