Module: Amountable::TableMethods

Extended by:
ActiveSupport::Autoload
Defined in:
lib/amountable/table_methods.rb

Instance Method Summary collapse

Instance Method Details

#get_set(name) ⇒ Object



53
54
55
# File 'lib/amountable/table_methods.rb', line 53

def get_set(name)
  find_amounts(self.amount_sets[name.to_sym]).sum(Money.zero, &:value)
end

#save(args = {}) ⇒ Object



22
23
24
25
26
# File 'lib/amountable/table_methods.rb', line 22

def save(args = {})
  ActiveRecord::Base.transaction do
    save_amounts if super(args)
  end
end

#save!(args = {}) ⇒ Object



28
29
30
31
32
# File 'lib/amountable/table_methods.rb', line 28

def save!(args = {})
  ActiveRecord::Base.transaction do
    save_amounts! if super(args)
  end
end

#save_amounts(bang: false) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/amountable/table_methods.rb', line 34

def save_amounts(bang: false)
  amounts_to_insert = []
  amounts.each do |amount|
    if amount.new_record?
      amount.amountable_id = self.id
      amounts_to_insert << amount
    else
      bang ? amount.save! : amount.save
    end
  end
  Amount.import(amounts_to_insert, timestamps: true, validate: false)
  amounts_to_insert.each do |amount|
    amount.instance_variable_set(:@new_record, false)
  end
  true
end

#save_amounts!Object



51
# File 'lib/amountable/table_methods.rb', line 51

def save_amounts!; save_amounts(bang: true); end

#set_amount(name, value) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/amountable/table_methods.rb', line 7

def set_amount(name, 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
  amount.value
end