Class: Mayak::Validations::Contract

Inherits:
Object
  • Object
show all
Extended by:
T::Generic, T::Sig
Defined in:
lib/mayak/validations/validation.rb

Constant Summary collapse

Value =
type_member
Error =
type_member

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rule_set = Set.new) ⇒ Contract

Returns a new instance of Contract.



17
18
19
# File 'lib/mayak/validations/validation.rb', line 17

def initialize(rule_set = Set.new)
  @rule_set = T.let(rule_set, T::Set[Rule[Value, [Symbol, Error]]])
end

Instance Attribute Details

#rule_setObject (readonly)

Returns the value of attribute rule_set.



14
15
16
# File 'lib/mayak/validations/validation.rb', line 14

def rule_set
  @rule_set
end

Instance Method Details

#check(value) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/mayak/validations/validation.rb', line 37

def check(value)
  initial = T.let(
    ::Mayak::ValidationResult::Valid[T::Hash[Symbol, Error]].new,
    ::Mayak::ValidationResult[T::Hash[Symbol, Error]]
  )
  rule_set.reduce(initial) do |aggreated_result, rule|
    current_result = Rule.with_keys_aggregated(rule).check(value)
    case aggreated_result
    when ::Mayak::ValidationResult::Valid
      current_result
    when ::Mayak::ValidationResult::Invalid
      case current_result
      when ::Mayak::ValidationResult::Valid
        aggreated_result
      when ::Mayak::ValidationResult::Invalid
        ::Mayak::ValidationResult::Invalid[T::Hash[Symbol, Error]].new(errors: [ ])
      else
        T.absurd(current_result)
      end
    else
      T.absurd(aggreated_result)
    end
  end
end

#validate(rule, key:, &blk) ⇒ Object



29
30
31
32
33
34
# File 'lib/mayak/validations/validation.rb', line 29

def validate(rule, key:, &blk)
  rule = Rule[Value, Error].new do |checked|
    rule.check(blk.call(checked))
  end
  Contract.new(rule_set.add(rule.with_key(key)))
end