Module: ActiveRecord::Money

Extended by:
ActiveSupport::Concern
Defined in:
lib/activerecord-money.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#blank_money?(value, options) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/activerecord-money.rb', line 22

def blank_money?(value, options)
  options[:allow_nil] and value.blank?
end

#currency_field(name, options) ⇒ Object



10
11
12
# File 'lib/activerecord-money.rb', line 10

def currency_field(name, options)
  options[:currency] || :"#{name}_currency"
end

#default_money_currency(options) ⇒ Object



6
7
8
# File 'lib/activerecord-money.rb', line 6

def default_money_currency(options)
  options[:default_currency] ||= Money.default_currency
end

#money_currency(name, options) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/activerecord-money.rb', line 14

def money_currency(name, options)
  attribute_name = currency_field(name, options)
  default_currency = default_money_currency(options)

  currency = respond_to?(attribute_name) ? send(attribute_name) : nil
  currency || default_currency
end

#money_reader(name, options = {}) ⇒ Object



26
27
28
29
# File 'lib/activerecord-money.rb', line 26

def money_reader(name, options = {})
  value = send("#{name}_in_cents")
  blank_money?(value, options) ? nil : Money.new(value || 0, money_currency(name, options))
end

#money_writer(name, value, options = {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/activerecord-money.rb', line 31

def money_writer(name, value, options = {})
  currency_attribute_name = currency_field(name, options)
  currency_name = money_currency(name, options)

  if value.is_a? Money
    send("#{name}_in_cents=", value.cents)
    send("#{currency_attribute_name}=", "#{value.currency.id}") if respond_to? "#{currency_attribute_name}="
  elsif !value.blank?
    value = value.to_money(currency_name)
    money_writer(name, value, options)
  else
    money_writer(name, 0.to_money(currency_name), options) unless blank_money?(name, options)
  end

  value
end