So, here's the situation: a rails app with two idioms, one where users use the format 5,000.40
for writing numbers (standard english), and the other 5.000,40
.
Now the question is, how do I deal with this? I'm using the i18n helpers for dealing with output, but I don't know how to process th开发者_运维百科ese numbers in my rails controller.
This is what I did to get this working:
Inside an initializer:
class ActiveRecord::Base
class << self
def handle_internationalization_numbers_for(*fields)
fields.each do |field_name|
define_method "#{field_name}=" do |other|
if valid_number?(other)
write_attribute(field_name, other)
else
# try converting it to a proper number
write_attribute(field_name, other.tr(".,", ",."))
end
end
end
end
end
private
def valid_number?(number)
number.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
end
Then in your models:
handle_internationalization_numbers_for :field_1, :field_2
Use the localize method
=l record.amount
and define the specific format in the locale files.
精彩评论