Class: Trafaret::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/trafaret/validator.rb

Direct Known Subclasses

ADT, Any, Array, Base, Case, Mapping, Nil, Numeric, Proc, String, Symbol, Tuple, URI

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &blk) ⇒ Validator

Returns a new instance of Validator.



4
5
6
7
8
9
10
11
# File 'lib/trafaret/validator.rb', line 4

def initialize(*args, &blk)
  @options = (args.pop if args.last.is_a? Hash) || {}
  @args = args
  @converters = []
  @converters << blk if blk

  prepare
end

Instance Attribute Details

#convertersObject

Returns the value of attribute converters.



2
3
4
# File 'lib/trafaret/validator.rb', line 2

def converters
  @converters
end

#optionsObject

Returns the value of attribute options.



2
3
4
# File 'lib/trafaret/validator.rb', line 2

def options
  @options
end

Instance Method Details

#&(other) ⇒ Object



64
65
66
# File 'lib/trafaret/validator.rb', line 64

def &(other)
  Trafaret::Chain.new(self, other)
end

#===(data) ⇒ Object



55
56
57
# File 'lib/trafaret/validator.rb', line 55

def ===(data)
  !validate(data).is_a?(Trafaret::Error)
end

#add(blk) ⇒ Object



46
47
48
# File 'lib/trafaret/validator.rb', line 46

def add(blk)
  @converters << blk
end

#call(data) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/trafaret/validator.rb', line 36

def call(data)
  val = validate(data)
  return val if val.is_a? Trafaret::Error
  if block_given?
    yield val
  else
    perform_convert(val)
  end
end

#convert(data) ⇒ Object



20
21
22
# File 'lib/trafaret/validator.rb', line 20

def convert(data)
  data
end

#failure(msg) ⇒ Object

Helpers



69
70
71
# File 'lib/trafaret/validator.rb', line 69

def failure(msg)
  Trafaret::Error.new msg
end

#perform_convert(data) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/trafaret/validator.rb', line 24

def perform_convert(data)
  if @converters.blank?
    convert(data)
  else
    @converters.each do |c|
      data = c.call(data)
      break if data.is_a? Trafaret::Error
    end
    data
  end
end

#prepareObject



13
14
# File 'lib/trafaret/validator.rb', line 13

def prepare
end

#to(&blk) ⇒ Object



50
51
52
53
# File 'lib/trafaret/validator.rb', line 50

def to (&blk)
  @converters << blk
  self
end

#validate(data) ⇒ Object



16
17
18
# File 'lib/trafaret/validator.rb', line 16

def validate(data)
  data # or return Trafaret::Error
end

#|(other) ⇒ Object

ADT



60
61
62
# File 'lib/trafaret/validator.rb', line 60

def |(other)
  Trafaret::Or.new(self, other)
end