Class: Assembler::Parameter

Inherits:
Object
  • Object
show all
Defined in:
lib/assembler/parameter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Parameter

Returns a new instance of Parameter.



5
6
7
8
# File 'lib/assembler/parameter.rb', line 5

def initialize(name, options = {})
  @name         = name.to_sym
  @options      = options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/assembler/parameter.rb', line 3

def name
  @name
end

Instance Method Details

#name_and_aliasesObject



10
11
12
# File 'lib/assembler/parameter.rb', line 10

def name_and_aliases
  @name_and_aliases ||= [name] + aliases.map(&:to_sym)
end

#value_from(hash, &if_required_and_missing) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/assembler/parameter.rb', line 14

def value_from(hash, &if_required_and_missing)
  @memoized_value_from ||= {}

  # NOTE: Jruby's Hash#hash implementation is BS:
  # {:foo => :foo}.hash => 1
  # {:bar => :bar}.hash => 1
  # {:foo => :foo}.to_a.hash => 806614226
  # {:bar => :bar}.to_a.hash => 3120054328
  # Go figure...
  memoization_key = hash.to_a.hash

  return @memoized_value_from[memoization_key] if @memoized_value_from[memoization_key]

  first_key = key_names.find { |name_or_alias| hash.has_key?(name_or_alias) }

  raw_value = hash.fetch(first_key) do
    options.fetch(:default) do
      if_required_and_missing.call unless if_required_and_missing.nil?

      # Returning here so we don't call coerce_value(nil)
      return
    end
  end

  @memoized_value_from[memoization_key] = coerce_value(raw_value)
end