Module: Invoicing::CurrencyValue::ActMethods

Defined in:
lib/invoicing/currency_value.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_currency_value(*args) ⇒ Object

Declares that the current model object has columns storing monetary amounts. Pass those attribute names to acts_as_currency_value. By default, we try to find an attribute or method called currency, which stores the 3-letter ISO 4217 currency code for a record; if that attribute has a different name, specify the name using the :currency option. For example:

class Price < ActiveRecord::Base
  validates_numericality_of :net_amount, :tax_amount
  validates_inclusion_of :currency_code, %w( USD GBP EUR JPY )
  acts_as_currency_value :net_amount, :tax_amount, :currency => :currency_code
end

You may also specify the :value_for_formatting option, passing it the name of a method on your model object. That method will be called when a CurrencyValue method with _formatted suffix is called, and allows you to modify the numerical value before it is formatted into a string. An options hash is also passed. This can be useful, for example, if a value is stored positive but you want to display it as negative in certain circumstances depending on the view:

class LedgerItem < ActiveRecord::Base
  acts_as_ledger_item
  acts_as_currency_value :total_amount, :tax_amount, :value_for_formatting => :value_for_formatting

  def value_for_formatting(value, options={})
    value *= -1 if options[:debit]  == :negative &&  debit?(options[:self_id])
    value *= -1 if options[:credit] == :negative && !debit?(options[:self_id])
    value
  end
end

invoice = Invoice.find(1)
invoice.total_amount_formatted :debit => :negative, :self_id => invoice.sender_id
  # => '$25.00'
invoice.total_amount_formatted :debit => :negative, :self_id => invoice.recipient_id
  # => '-$25.00'

(The example above is actually a real part of LedgerItem.)


112
113
114
115
116
117
# File 'lib/invoicing/currency_value.rb', line 112

def acts_as_currency_value(*args)
  Invoicing::ClassInfo.acts_as(Invoicing::CurrencyValue, self, args)

  # Register callback if this is the first time acts_as_currency_value has been called
  before_save :write_back_currency_values if currency_value_class_info.previous_info.nil?
end