Class: Amount::Registry::GeneratedConstructors

Inherits:
Object
  • Object
show all
Defined in:
lib/amount/registry/generated_constructors.rb

Overview

Manages registry-driven constructor methods such as ‘Amount.of_usdc(…)`.

Generated names are prefixed with ‘of_` so that short ISO codes like `:TRY` (which collides with `Object#try` once ActiveSupport is loaded) do not clash with existing methods on `Amount`.

Constant Summary collapse

SYMBOL_PATTERN =
/\A[a-z_][a-z0-9_]*\z/
METHOD_NAME_PREFIX =
"of_"

Instance Method Summary collapse

Constructor Details

#initialize(target: Amount) ⇒ GeneratedConstructors

Returns a new instance of GeneratedConstructors.



14
15
16
17
# File 'lib/amount/registry/generated_constructors.rb', line 14

def initialize(target: Amount)
  @target = target
  @method_names = []
end

Instance Method Details

#activate(entries) ⇒ Object



33
34
35
# File 'lib/amount/registry/generated_constructors.rb', line 33

def activate(entries)
  entries.each_value { |entry| define_for(entry) }
end

#define_for(entry) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/amount/registry/generated_constructors.rb', line 19

def define_for(entry)
  method_name = method_name_for(entry.symbol)
  return unless method_name

  raise_collision!(method_name)

  @target.define_singleton_method(method_name) do |value, **opts|
    resolved_entry = registry.lookup(entry.symbol)
    resolved_entry.amount_class.new(value, entry.symbol, **opts)
  end

  @method_names << method_name.to_sym
end

#remove_allObject



37
38
39
40
41
42
43
# File 'lib/amount/registry/generated_constructors.rb', line 37

def remove_all
  @method_names.each do |method_name|
    remove_method(method_name)
  end

  @method_names.clear
end