Handling cases when , used instead of . more elegantly

bundler
Sam Lown 2010-10-23 20:59:24 +02:00
parent ef6f54d966
commit e8d7af9896
3 changed files with 18 additions and 1 deletions

View File

@ -7,6 +7,7 @@
* Minor enhancements
* Fixing find("") issue (thanks epochwolf)
* Altered protected attributes so that hash provided to #attributes= is not modified
* Altering typecasting for floats to better handle commas and points
Notes:

View File

@ -79,7 +79,7 @@ module CouchRest
# Match numeric string
def typecast_to_numeric(value, method)
if value.respond_to?(:to_str)
if value.to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/
if value.gsub(/,/, '.').gsub(/\.(?!\d*\Z)/, '').to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/
$1.send(method)
else
value

View File

@ -320,12 +320,28 @@ describe "Model properties" do
@course['estimate'].should eql(-24.35)
end
it 'return float of a number with commas instead of points for decimals' do
@course.estimate = '23,35'
@course['estimate'].should eql(23.35)
end
it "should handle numbers with commas and points" do
@course.estimate = '1,234.00'
@course.estimate.should eql(1234.00)
end
it "should handle a mis-match of commas and points and maintain the last one" do
@course.estimate = "1,232.434.123,323"
@course.estimate.should eql(1232434123.323)
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.estimate = value
@course['estimate'].should equal(value)
end
end
end
describe 'when type primitive is a Integer' do