Class: Meta::Utils::Kwargs::ArgumentConsumer

Inherits:
Object
  • Object
show all
Defined in:
lib/meta/utils/kwargs/consumers.rb

Constant Summary collapse

DEFAULT_TRANSFORMER =
->(value) { value }

Instance Method Summary collapse

Constructor Details

#initialize(name:, normalizer: DEFAULT_TRANSFORMER, validator: nil, default: nil, alias_names: []) ⇒ ArgumentConsumer

Returns a new instance of ArgumentConsumer.



9
10
11
12
13
14
15
# File 'lib/meta/utils/kwargs/consumers.rb', line 9

def initialize(name:, normalizer: DEFAULT_TRANSFORMER, validator: nil, default: nil, alias_names: [])
  @key_name = name
  @consumer_names = [name] + alias_names
  @default_proc = -> { default.dup } if default
  @normalizer = normalizer
  @validator = validator
end

Instance Method Details

#consume(final_args, args) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/meta/utils/kwargs/consumers.rb', line 17

def consume(final_args, args)
  @consumer_names.each do |name|
    return if consume_name(final_args, args, name)
  end

  if @default_proc
    default_value = @default_proc.call
    final_args[@key_name] = @normalizer.call(default_value)
  end
end

#consume_name(final_args, args, consumer_name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/meta/utils/kwargs/consumers.rb', line 28

def consume_name(final_args, args, consumer_name)
  if args.key?(consumer_name)
    value = @normalizer.call(args.delete(consumer_name))
    @validator.call(value) if @validator
    final_args[@key_name] = value
    true
  else
    false
  end
end