Class: Trafaret::Constructor

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

Class Method Summary collapse

Class Method Details

.construct_from(from) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/trafaret/constructor.rb', line 4

def construct_from(from)
  case from
  when ::Hash
    from_hash(from)
  when ::Array
    from_array(from)
  when ::Symbol
    Trafaret.get_instantiated_validator from
  when Trafaret::Validator
    from
  when ::Proc
    Trafaret::Proc.new &from
  else
    raise 'Wrong parameter'
  end
end

.from_array(params) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/trafaret/constructor.rb', line 35

def from_array(params)
  if params.size == 1
    Trafaret::Array.new validator: Trafaret::Constructor.construct_from(params[0])
  else params.size > 1
    Trafaret::Tuple.new(*(params.map { |p| Trafaret::Constructor.construct_from(p) }))
  end
end

.from_hash(params) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/trafaret/constructor.rb', line 21

def from_hash(params)
  keys = []
  params.each do |k, v|
    v = Trafaret::Constructor.construct_from v
    if k.is_a? ::Symbol
      keys << Key.new(k, v)
    elsif k.is_a? Trafaret::Key
      k.set_validator(v)
      keys << k
    end
  end
  Trafaret::Base.new keys: keys
end