Module: Amountable::ClassMethods

Defined in:
lib/amountable.rb

Instance Method Summary collapse

Instance Method Details

#allowed_amount_name?(name) ⇒ Boolean

Returns:

  • (Boolean)


124
125
126
# File 'lib/amountable.rb', line 124

def allowed_amount_name?(name)
  self.amount_names.include?(name.to_sym)
end

#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

#amount_set(set_name, component) ⇒ Object



89
90
91
92
93
94
95
# File 'lib/amountable.rb', line 89

def amount_set(set_name, component)
  self.amount_sets[set_name.to_sym] << component.to_sym

  define_method set_name do
    find_amounts(self.amount_sets[set_name.to_sym]).sum(Money.zero, &:value)
  end
end