Commit f88dad03825e0e8aadb17d0b902239cd3781c142
Committed by
Antonio Terceiro
1 parent
6a196432
Exists in
master
and in
29 other branches
Products accepts prices in brazilian's or american's format
* Brazilian's currency format: 123.456,78 * American's currency format: 123,456.78 ActionItem1322
Showing
2 changed files
with
47 additions
and
0 deletions
Show diff stats
app/models/product.rb
@@ -67,4 +67,36 @@ class Product < ActiveRecord::Base | @@ -67,4 +67,36 @@ class Product < ActiveRecord::Base | ||
67 | enterprise.public_profile | 67 | enterprise.public_profile |
68 | end | 68 | end |
69 | 69 | ||
70 | + def price=(value) | ||
71 | + if value.is_a?(String) | ||
72 | + super(currency_to_float(value)) | ||
73 | + else | ||
74 | + super(value) | ||
75 | + end | ||
76 | + end | ||
77 | + | ||
78 | + def currency_to_float( num ) | ||
79 | + if num.count('.') == 1 && num.count(',') == 0 | ||
80 | + # number like "12.34" | ||
81 | + return num.to_f | ||
82 | + end | ||
83 | + | ||
84 | + if num.count('.') == 0 && num.count(',') == 1 | ||
85 | + # number like "12,34" | ||
86 | + return num.tr(',','.').to_f | ||
87 | + end | ||
88 | + | ||
89 | + if num.count('.') > 0 && num.count(',') > 0 | ||
90 | + # number like "12.345.678,90" or "12,345,678.90" | ||
91 | + dec_sep = num.tr('0-9','')[-1].chr | ||
92 | + return num.tr('^0-9'+dec_sep,'').tr(dec_sep,'.').to_f | ||
93 | + end | ||
94 | + | ||
95 | + # if you are here is because there is only one | ||
96 | + # separator and this appears 2 times or more. | ||
97 | + # number like "12.345.678" or "12,345,678" | ||
98 | + | ||
99 | + return num.tr(',.','').to_f | ||
100 | + end | ||
101 | + | ||
70 | end | 102 | end |
test/unit/product_test.rb
@@ -178,4 +178,19 @@ class ProductTest < Test::Unit::TestCase | @@ -178,4 +178,19 @@ class ProductTest < Test::Unit::TestCase | ||
178 | assert !p1.public? | 178 | assert !p1.public? |
179 | end | 179 | end |
180 | 180 | ||
181 | + should 'accept prices in american\'s or brazilian\'s currency format' do | ||
182 | + [ | ||
183 | + [12.34, 12.34], | ||
184 | + ["12.34", 12.34], | ||
185 | + ["12,34", 12.34], | ||
186 | + ["12.345.678,90", 12345678.90], | ||
187 | + ["12,345,678.90", 12345678.90], | ||
188 | + ["12.345.678", 12345678.00], | ||
189 | + ["12,345,678", 12345678.00] | ||
190 | + ].each do |input, output| | ||
191 | + product = Product.new(:price => input) | ||
192 | + assert_equal output, product.price | ||
193 | + end | ||
194 | + end | ||
195 | + | ||
181 | end | 196 | end |