Handling cases when , used instead of . more elegantly

This commit is contained in:
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 * Minor enhancements
* Fixing find("") issue (thanks epochwolf) * Fixing find("") issue (thanks epochwolf)
* Altered protected attributes so that hash provided to #attributes= is not modified * Altered protected attributes so that hash provided to #attributes= is not modified
* Altering typecasting for floats to better handle commas and points
Notes: Notes:

View file

@ -79,7 +79,7 @@ module CouchRest
# Match numeric string # Match numeric string
def typecast_to_numeric(value, method) def typecast_to_numeric(value, method)
if value.respond_to?(:to_str) 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) $1.send(method)
else else
value value

View file

@ -320,12 +320,28 @@ describe "Model properties" do
@course['estimate'].should eql(-24.35) @course['estimate'].should eql(-24.35)
end 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| [ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do it "does not typecast non-numeric value #{value.inspect}" do
@course.estimate = value @course.estimate = value
@course['estimate'].should equal(value) @course['estimate'].should equal(value)
end end
end end
end end
describe 'when type primitive is a Integer' do describe 'when type primitive is a Integer' do