Module: Validation::Adjustment

Defined in:
lib/validation/adjustment.rb

Support Building Adjusters collapse

Class Method Details

.adjustable?(object) ⇒ Boolean

true if argument is sufficient for adjuster. A adjuster have to be arity equal 1.

Returns:

  • (Boolean)

13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/validation/adjustment.rb', line 13

def adjustable?(object)
  case object
  when Proc
    object.arity == 1
  else
    if object.respond_to? :to_proc
      object.to_proc.arity == 1
    else
      false
    end
  end
end

.INJECT(adjuster1, adjuster2, *adjusters) ⇒ lambda

Sequencial apply all adjusters.

Parameters:

  • adjuster1 (Proc, #to_proc)
  • adjuster2 (Proc, #to_proc)
  • adjusters (Proc, #to_proc)

Returns:

  • (lambda)

48
49
50
51
52
53
54
55
56
57
58
# File 'lib/validation/adjustment.rb', line 48

def INJECT(adjuster1, adjuster2, *adjusters)
  adjusters = [adjuster1, adjuster2, *adjusters]

  unless adjusters.all?{|f|adjustable? f}
    raise TypeError, 'wrong object for adjuster'
  end

  ->v{
    adjusters.reduce(v){|ret, adjuster|adjuster.call ret}
  }
end

.PARSE(parser) ⇒ lambda

Accept any parser when that resopond to parse method.

Parameters:

  • parser (#parse)

Returns:

  • (lambda)

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/validation/adjustment.rb', line 63

def PARSE(parser)
  if !::Integer.equal?(parser) and !parser.respond_to?(:parse)
    raise TypeError, 'wrong object for parser'
  end
  
  ->v{
    if ::Integer.equal? parser
      ::Kernel.Integer v
    else
      parser.parse(
        case v
        when String
          v
        when ->_{v.respond_to? :to_str}
          v.to_str
        when ->_{v.respond_to? :read}
          v.read            
        else
          raise TypeError, 'wrong object for parsing source'
        end
      )
    end
  }
end

.WHEN(condition, adjuster) ⇒ lambda

Adjuster Builders Apply adjuster when passed condition.

Parameters:

  • condition (Proc, Method, #===)
  • adjuster (Proc, #to_proc)

Returns:

  • (lambda)

31
32
33
34
35
36
37
38
39
40
41
# File 'lib/validation/adjustment.rb', line 31

def WHEN(condition, adjuster)
  unless Validation.conditionable? condition
    raise TypeError, 'wrong object for condition' 
  end

  unless Validation.adjustable? adjuster
    raise TypeError, 'wrong object for adjuster' 
  end
  
  ->v{_valid?(condition, v) ? adjuster.call(v) : v}
end