From f88dad03825e0e8aadb17d0b902239cd3781c142 Mon Sep 17 00:00:00 2001 From: Rodrigo Souto Date: Thu, 26 Nov 2009 09:57:39 -0300 Subject: [PATCH] Products accepts prices in brazilian's or american's format --- app/models/product.rb | 32 ++++++++++++++++++++++++++++++++ test/unit/product_test.rb | 15 +++++++++++++++ 2 files changed, 47 insertions(+), 0 deletions(-) diff --git a/app/models/product.rb b/app/models/product.rb index ec41f49..84529f2 100644 --- a/app/models/product.rb +++ b/app/models/product.rb @@ -67,4 +67,36 @@ class Product < ActiveRecord::Base enterprise.public_profile end + def price=(value) + if value.is_a?(String) + super(currency_to_float(value)) + else + super(value) + end + end + + def currency_to_float( num ) + if num.count('.') == 1 && num.count(',') == 0 + # number like "12.34" + return num.to_f + end + + if num.count('.') == 0 && num.count(',') == 1 + # number like "12,34" + return num.tr(',','.').to_f + end + + if num.count('.') > 0 && num.count(',') > 0 + # number like "12.345.678,90" or "12,345,678.90" + dec_sep = num.tr('0-9','')[-1].chr + return num.tr('^0-9'+dec_sep,'').tr(dec_sep,'.').to_f + end + + # if you are here is because there is only one + # separator and this appears 2 times or more. + # number like "12.345.678" or "12,345,678" + + return num.tr(',.','').to_f + end + end diff --git a/test/unit/product_test.rb b/test/unit/product_test.rb index f7ce3d9..bdb3ae2 100644 --- a/test/unit/product_test.rb +++ b/test/unit/product_test.rb @@ -178,4 +178,19 @@ class ProductTest < Test::Unit::TestCase assert !p1.public? end + should 'accept prices in american\'s or brazilian\'s currency format' do + [ + [12.34, 12.34], + ["12.34", 12.34], + ["12,34", 12.34], + ["12.345.678,90", 12345678.90], + ["12,345,678.90", 12345678.90], + ["12.345.678", 12345678.00], + ["12,345,678", 12345678.00] + ].each do |input, output| + product = Product.new(:price => input) + assert_equal output, product.price + end + end + end -- libgit2 0.21.2