Module: Amountable::JsonbMethods
- Extended by:
- ActiveSupport::Autoload
- Defined in:
- lib/amountable/jsonb_methods.rb
Instance Method Summary collapse
- #amounts ⇒ Object
- #get_set(name) ⇒ Object
- #initialize_column ⇒ Object
- #refresh_sets ⇒ Object
- #set_amount(name, value) ⇒ Object
- #set_json(json) ⇒ Object
Instance Method Details
#amounts ⇒ Object
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| Amount.new(name: name, value_cents: amount['cents'], value_currency: amount['value_currency'], persistable: false, amountable: self) end.to_set end |
#get_set(name) ⇒ Object
38 39 40 41 |
# File 'lib/amountable/jsonb_methods.rb', line 38 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'] || 'USD') end |
#initialize_column ⇒ Object
47 48 49 |
# File 'lib/amountable/jsonb_methods.rb', line 47 def initialize_column send("#{amounts_column_name}=", {}) if attribute(amounts_column_name).nil? end |
#refresh_sets ⇒ Object
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/amountable/jsonb_methods.rb', line 27 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) 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 |
# File 'lib/amountable/jsonb_methods.rb', line 13 def set_amount(name, value) value = value.to_money return value if value.zero? initialize_column amounts_json = attribute(amounts_column_name) amounts_json['amounts'] ||= {} amounts_json['amounts'][name.to_s] = {'cents' => value.fractional, 'currency' => value.currency.iso_code} set_json(amounts_json) @_amounts = nil @amounts_by_name = nil refresh_sets value end |
#set_json(json) ⇒ Object
43 44 45 |
# File 'lib/amountable/jsonb_methods.rb', line 43 def set_json(json) send("#{amounts_column_name}=", json) end |