Class: Ree::Contracts::ArgContracts::SetOf

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Squarable

[]

Methods included from Truncatable

#truncate

Constructor Details

#initialize(*contracts) ⇒ SetOf

Returns a new instance of SetOf.



13
14
15
16
17
18
19
# File 'lib/ree/contracts/arg_contracts/set_of.rb', line 13

def initialize(*contracts)
  if contracts.size != 1
    raise BadContractError, 'SetOf should accept exactly one contract'
  end

  @validator = Validators.fetch_for(contracts.first)
end

Instance Attribute Details

#validatorObject (readonly)

Returns the value of attribute validator.



11
12
13
# File 'lib/ree/contracts/arg_contracts/set_of.rb', line 11

def validator
  @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
# File 'lib/ree/contracts/arg_contracts/set_of.rb', line 30

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

  errors = []
  sps = "  " * lvl

  value.each_with_index do |val, idx|
    next if validator.call(val)

    msg = validator.message(val, "#{name}[#{idx}]", lvl + 1)
    errors << "\n\t#{sps} - #{name}[#{idx}]: #{msg}"

    if errors.size > 3
      errors << "\n\t#{sps} - ..."
      break
    end
  end

  errors.join
end

#to_sObject



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

def to_s
  "SetOf[#{validator.to_s}]"
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


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

def valid?(value)
  value.is_a?(Set) &&
    value.all?(&validator.method(:call))
end