Last active
May 17, 2018 21:45
-
-
Save brunofrank/fa2b125cc7d4880deed86db620b352de to your computer and use it in GitHub Desktop.
Helps to apply i18n in numbers and money formats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Put on config/initializers folder | |
class String | |
def to_delocalized_decimal | |
delimiter = I18n::t('number.format.delimiter') | |
separator = I18n::t('number.format.separator') | |
self.gsub(/[#{delimiter}]/, '').gsub(separator, '.') | |
end | |
def to_delocalized_money | |
unit = I18n::t('number.currency.format.unit') | |
delimiter = I18n::t('number.currency.format.delimiter') | |
separator = I18n::t('number.currency.format.separator') | |
self.gsub(/[#{unit} ?#{delimiter}]/, '').gsub(separator, '.') | |
end | |
end | |
class ActiveRecord::Base | |
def self.localized_number(*fields) | |
fields.each do |field| | |
define_method("#{field}=") do |value| | |
self[field] = value.is_a?(String) ? value.to_delocalized_decimal : value | |
end | |
end | |
end | |
def self.localized_money(*fields) | |
fields.each do |field| | |
define_method("#{field}=") do |value| | |
self[field] = value.is_a?(String) ? value.to_delocalized_money : value | |
end | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pt-BR: | |
number: | |
currency: | |
format: | |
delimiter: "." | |
separator: "," | |
unit: R$ | |
format: | |
delimiter: "." | |
separator: "," |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment