Method: Amountable::ClassMethods#amount

Defined in:
lib/amountable.rb

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



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/amountable.rb', line 97

def amount(name, options = {})
  (self.amount_names ||= Set.new) << name

  define_method name do
    (find_amount(name) || NilAmount.new).value
  end

  define_method "#{name}=" do |value|
    amount = find_amount(name) || amounts.build(name: name)
    amount.value = value.to_money
    if value.zero?
      amounts.delete(amount)
      all_amounts.delete(amount)
      @amounts_by_name.delete(name)
      amount.destroy if amount.persisted?
    else
      all_amounts << amount if amount.new_record?
      (@amounts_by_name ||= {})[name.to_sym] = amount
    end
    value.to_money
  end

  Array(options[:summable] || options[:summables] || options[:set] || options[:sets] || options[:amount_set] || options[:amount_sets]).each do |set|
    amount_set(set, name)
  end
end