Class: Ree::Contracts::ArgContracts::SplatOf

Inherits:
Object
  • Object
show all
Includes:
Truncatable
Defined in:
lib/ree/contracts/arg_contracts/splat_of.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Truncatable

#truncate

Constructor Details

#initialize(contract) ⇒ SplatOf

Returns a new instance of SplatOf.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ree/contracts/arg_contracts/splat_of.rb', line 16

def initialize(contract)
  forbidden_class_contracts = Ree::Contracts::Validators::FORBIDDEN_CONTRACTS

  contract_name = if forbidden_class_contracts.include?(contract)
    contract.to_s
  elsif forbidden_class_contracts.include?(contract.class)
    contract.class.to_s
  end

  if contract_name
    raise BadContractError, "#{contract_name} contract is not allowed to use inside SplatOf contract"
  end

  @validator = Validators.fetch_for(contract)
end

Instance Attribute Details

#validatorObject (readonly)

Returns the value of attribute validator.



8
9
10
# File 'lib/ree/contracts/arg_contracts/splat_of.rb', line 8

def validator
  @validator
end

Class Method Details

.[](contract) ⇒ Object



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

def [](contract)
  new(contract)
end

Instance Method Details

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



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ree/contracts/arg_contracts/splat_of.rb', line 40

def message(value, name, lvl = 1)
  unless value.is_a?(Array)
    return "expected #{to_s}, 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



36
37
38
# File 'lib/ree/contracts/arg_contracts/splat_of.rb', line 36

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

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/ree/contracts/arg_contracts/splat_of.rb', line 32

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