Class: Ree::Contracts::ArgContracts::HashOf

Inherits:
Object
  • Object
show all
Extended by:
Squarable
Includes:
Truncatable
Defined in:
lib/ree/contracts/arg_contracts/hash_of.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Squarable

[]

Methods included from Truncatable

#truncate

Constructor Details

#initialize(*contracts) ⇒ HashOf

Returns a new instance of HashOf.



11
12
13
14
15
16
17
18
# File 'lib/ree/contracts/arg_contracts/hash_of.rb', line 11

def initialize(*contracts)
  if contracts.size != 2
    raise BadContractError, 'HashOf should accept exactly two contracts'
  end

  @key_validator   = Validators.fetch_for(contracts[0])
  @value_validator = Validators.fetch_for(contracts[1])
end

Instance Attribute Details

#key_validatorObject (readonly)

Returns the value of attribute key_validator.



9
10
11
# File 'lib/ree/contracts/arg_contracts/hash_of.rb', line 9

def key_validator
  @key_validator
end

#value_validatorObject (readonly)

Returns the value of attribute value_validator.



9
10
11
# File 'lib/ree/contracts/arg_contracts/hash_of.rb', line 9

def value_validator
  @value_validator
end

Instance Method Details

#message(value, name, lvl = 1) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ree/contracts/arg_contracts/hash_of.rb', line 30

def message(value, name, lvl = 1)
  unless value.is_a?(Hash)
    return "expected Hash, got #{value.class} => #{truncate(value.inspect)}"
  end

  errors = []
  sps = "  " * lvl

  value.each do |key, val|
    if errors.size > 4
      errors << "\n\t#{sps} - ..."
      break
    end

    unless key_validator.call(key)
      msg = key_validator.message(key, "#{name}[#{key.inspect}]", lvl + 1)
      errors << "\n\t#{sps} - invalid key #{key.inspect}, #{msg}"
    end

    unless value_validator.call(val)
      msg = key_validator.message(val, "#{name}[#{key.inspect}]", lvl + 1)
      errors << "\n\t#{sps} - invalid value for #{key.inspect} key, #{msg}"
    end
  end

  errors.join
end

#to_sObject



26
27
28
# File 'lib/ree/contracts/arg_contracts/hash_of.rb', line 26

def to_s
  "HashOf[#{key_validator.to_s}, #{value_validator.to_s}]"
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
# File 'lib/ree/contracts/arg_contracts/hash_of.rb', line 20

def valid?(value)
  value.is_a?(Hash) &&
    value.each_key.all?(&key_validator.method(:call)) &&
    value.each_value.all?(&value_validator.method(:call))
end