Module: MoneyAttribute::Macro::CompositeClassMethods

Defined in:
lib/money_attribute/macro.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#assert_columns_exist!(name, mapping) ⇒ Object

Raises when the resolved columns are not present on the model.

Raises:

  • (ArgumentError)


49
50
51
52
53
54
55
56
57
# File 'lib/money_attribute/macro.rb', line 49

def assert_columns_exist!(name, mapping)
  missing = mapping.values - column_names
  return if missing.empty?

  raise ArgumentError,
        "Could not find columns for :#{name} money attribute. " \
        "Expected: #{mapping.values.join(', ')}, " \
        "Found: #{attribute_names.join(', ')}"
end

#default_mapping(name) ⇒ Object

Returns the default amount/currency mapping for the attribute name.



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/money_attribute/macro.rb', line 23

def default_mapping(name)
  name = name.to_s
  names = column_names

  if names.include?("#{name}_currency") && names.include?(name)
    { amount: name, currency: "#{name}_currency" }
  elsif name == 'amount' && names.include?('currency')
    { amount: name, currency: 'currency' }
  else
    { amount: "#{name}_amount", currency: "#{name}_currency" }
  end
end

#register_composite_spec(name, mapping) ⇒ Object

Registers the composite money attribute spec for the model.



37
38
39
40
41
42
43
44
45
46
# File 'lib/money_attribute/macro.rb', line 37

def register_composite_spec(name, mapping)
  column = column_for_attribute(mapping[:amount])
  register_money_attribute_spec(
    name,
    kind: :composite,
    amount_col: mapping[:amount],
    currency_col: mapping[:currency],
    amount_type: %i[integer bigint].include?(column.type) ? :integer : :decimal
  )
end

#resolve_mapping(name, mapping_override) ⇒ Object

Normalizes the requested mapping by applying conventions and overrides.



11
12
13
14
15
16
17
18
19
20
# File 'lib/money_attribute/macro.rb', line 11

def resolve_mapping(name, mapping_override)
  override = mapping_override.compact
  override.slice!(:amount, :currency)
  override.transform_values!(&:to_s)

  mapping = default_mapping(name).merge(override)

  assert_columns_exist!(name, mapping)
  mapping
end