Class: Code::Type::Hash

Inherits:
Code::Type show all
Defined in:
lib/code/type/hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Code::Type

#max_arguments_of, #maybe, #min_arguments_of, #repeat, #valid_for?, #|

Constructor Details

#initialize(hash) ⇒ Hash

Returns a new instance of Hash.



8
9
10
# File 'lib/code/type/hash.rb', line 8

def initialize(hash)
  @hash = hash.transform_keys { |key| Object::String.new(key) }
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



6
7
8
# File 'lib/code/type/hash.rb', line 6

def hash
  @hash
end

Instance Method Details

#max_argumentsObject



32
33
34
# File 'lib/code/type/hash.rb', line 32

def max_arguments
  hash.sum { |_, value| max_arguments_of(value) }
end

#min_argumentsObject



28
29
30
# File 'lib/code/type/hash.rb', line 28

def min_arguments
  hash.sum { |_, value| min_arguments_of(value) }
end

#nameObject



36
37
38
# File 'lib/code/type/hash.rb', line 36

def name
  "{#{hash.map { |key, value| "#{key.inspect} => #{value.name}" }.join(", ")}}"
end

#valid?(argument) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/code/type/hash.rb', line 12

def valid?(argument)
  return false unless argument.is_a?(Object::Dictionary)

  argument = argument.raw
  (argument.keys + hash.keys).uniq.all? do |key|
    if hash[key]
      valid_for?(
        expected: hash[key],
        actual: argument[key] || Object::Nothing.new
      )
    else
      false
    end
  end
end