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.usdc(…)`.

Constant Summary collapse

METHOD_NAME_PATTERN =
/\A[a-z_][a-z0-9_]*\z/

Instance Method Summary collapse

Constructor Details

#initialize(target: Amount) ⇒ GeneratedConstructors

Returns a new instance of GeneratedConstructors.



9
10
11
12
# File 'lib/amount/registry/generated_constructors.rb', line 9

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

Instance Method Details

#activate(entries) ⇒ Object



28
29
30
# File 'lib/amount/registry/generated_constructors.rb', line 28

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

#define_for(entry) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/amount/registry/generated_constructors.rb', line 14

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



32
33
34
35
36
37
38
# File 'lib/amount/registry/generated_constructors.rb', line 32

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

  @method_names.clear
end