Module: Danconia::Integrations::ActiveRecord::ClassMethods

Defined in:
lib/danconia/integrations/active_record.rb

Instance Method Summary collapse

Instance Method Details

#money(*attr_names) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/danconia/integrations/active_record.rb', line 11

def money(*attr_names)
  attr_names.each do |attr_name|
    amount_column = attr_name
    currency_column = "#{attr_name}_currency"

    class_eval <<-EOR, __FILE__, __LINE__ + 1
      def #{attr_name}= value
        write_attribute :#{amount_column}, value.is_a?(Money) ? value.amount : value
        write_attribute :#{currency_column}, value.currency.code if respond_to?(:#{currency_column}) && value.is_a?(Money)
      end

      def #{attr_name}
        amount = read_attribute :#{amount_column}
        currency = read_attribute :#{currency_column}
        decimals = self.class.columns.detect { |c| c.name == '#{amount_column}' }.scale
        Money.new amount, currency, decimals: decimals if amount
      end
    EOR
  end
end