Lidando com números e moedas localizadas

Bráulio Bhavamitra brauliobhavamitra at gmail.com
Fri Mar 15 12:01:04 BRT 2013


Olá pessoal,

Nos coletivos de consumo usamos muito preços e quantidades em campos para
visualização e edição. Para facilitar criamos uma estrutura que pode ser
futuramente generalizada no noosfero.

A estrutura permite conversões de ida e volta para números localizados de
forma mais transparente, por exemplo:

I18n.locale = :pt
product.price #=> 2.1
product.price_as_currency #=> "R$ 2,10"
product.price_as_currency_without_unit #=> "2,10"
product.price = "R$ 2,50"
product.price #=> 2.50

Seu uso nos modelos:
extend DistributionPlugin::DistributionCurrencyHelper::ClassMethods
   has_number_with_locale :minimum_selleable
   has_currency :price

abraços,
bráulio


Módulo fonte:
module DistributionPlugin::DistributionCurrencyHelper

  def self.parse_localized_number number
    return number if number.is_a?(Float)
    number.gsub(I18n.t("number.currency.format.unit"),
'').gsub(I18n.t("number.currency.format.delimiter"),
'').gsub(I18n.t("number.currency.format.
...separator"), '.').to_f
  end

  def self.parse_currency currency
    self.parse_localized_number currency
  end

  module ClassMethods

    def has_number_with_locale field
      define_method "#{field}=" do |value|
        self[field] =
DistributionPlugin::DistributionCurrencyHelper.parse_localized_number value
      end
    end

    def has_currency field
      self.has_number_with_locale field

      define_method "#{field}_as_currency_without_unit" do |*args, &block|
        number = send(field, *args, &block) rescue self[field]
        ActionController::Base.helpers.number_to_currency(number, :unit =>
'').gsub(' ', '')
      end
      define_method "#{field}_as_currency" do |*args, &block|
        number = send(field, *args, &block) rescue self[field]
        ActionController::Base.helpers.number_to_currency(number)
      end
    end

  end

  module InstanceMethods

  end

end
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://listas.softwarelivre.org/pipermail/noosfero-br/attachments/20130315/b50b17b6/attachment.html>


More information about the Noosfero-br mailing list