Module: SmartEnum::MonetizeInterop

Defined in:
lib/smart_enum/monetize_interop.rb

Constant Summary collapse

CENTS_SUFFIX =
/_cents\z/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.disable_memoization!Object



44
45
46
# File 'lib/smart_enum/monetize_interop.rb', line 44

def self.disable_memoization!
  @memoize_method_value = false
end

.memoize_method_valueObject



40
41
42
# File 'lib/smart_enum/monetize_interop.rb', line 40

def self.memoize_method_value
  @memoize_method_value
end

Instance Method Details

#monetize(cents_field_name, as: nil, **opts) ⇒ Object

Note: this ignores the currency column since we only ever monetize things as USD. If that changes this should start reading the currency column.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/smart_enum/monetize_interop.rb', line 12

def monetize(cents_field_name, as: nil, **opts)
  if opts.any?
    fail "unsupported options: #{opts.keys.join(',')}"
  end

  attr_def = attribute_set[cents_field_name.to_sym]
  if !attr_def
    fail "no attribute called #{cents_field_name}, (Do you need to add '_cents'?)"
  end

  if attr_def.types != INTEGER
    fail "attribute #{cents_field_name.inspect} can't monetize, only Integer is allowed"
  end

  money_attribute = as || cents_field_name.to_s.sub(CENTS_SUFFIX, '')

  define_method(money_attribute) do
    if MonetizeInterop.memoize_method_value
      @money_cache ||= {}
      @money_cache[money_attribute] ||= Money.new(public_send(cents_field_name))
    else
      Money.new(public_send(cents_field_name))
    end
  end
end