Module: Amountable::JsonbMethods

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

Instance Method Summary collapse

Instance Method Details

#amountsObject



7
8
9
10
11
# File 'lib/amountable/jsonb_methods.rb', line 7

def amounts
  @_amounts ||= attribute(amounts_column_name).to_h['amounts'].to_h.map do |name, amount|
    Amountable::VirtualAmount.new(name: name, value_cents: amount['cents'], value_currency: amount['currency'], persistable: false, amountable: self)
  end.to_set
end

#get_set(name) ⇒ Object



42
43
44
45
# File 'lib/amountable/jsonb_methods.rb', line 42

def get_set(name)
  value = attribute(amounts_column_name).to_h['sets'].to_h[name.to_s].to_h
  Money.new(value['cents'].to_i, value['currency'])
end

#initialize_columnObject



51
52
53
# File 'lib/amountable/jsonb_methods.rb', line 51

def initialize_column
  send("#{amounts_column_name}=", {}) if attribute(amounts_column_name).nil?
end

#refresh_setsObject



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/amountable/jsonb_methods.rb', line 30

def refresh_sets
  initialize_column
  amounts_json = attribute(amounts_column_name)
  amounts_json['sets'] = {}
  amount_sets.each do |name, amount_names|
    sum = find_amounts(amount_names).sum(Money.zero, &:value)
    next if sum.zero?
    amounts_json['sets'][name.to_s] = {'cents' => sum.fractional, 'currency' => sum.currency.iso_code}
  end
  set_json(amounts_json)
end

#set_amount(name, value) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/amountable/jsonb_methods.rb', line 13

def set_amount(name, value)
  value = value.to_money
  initialize_column
  amounts_json = attribute(amounts_column_name)
  amounts_json['amounts'] ||= {}
  if value.zero?
    amounts_json['amounts'].delete(name.to_s)
  else
    amounts_json['amounts'][name.to_s] = {'cents' => value.fractional, 'currency' => value.currency.iso_code}
  end
  set_json(amounts_json)
  @_amounts = nil
  @amounts_by_name = nil
  refresh_sets
  value
end

#set_json(json) ⇒ Object



47
48
49
# File 'lib/amountable/jsonb_methods.rb', line 47

def set_json(json)
  send("#{amounts_column_name}=", json)
end