Class: React::Validator

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeValidator

Returns a new instance of Validator.



9
10
11
# File 'lib/react/validator.rb', line 9

def initialize
  @rules = {}
end

Class Method Details

.build(&block) ⇒ Object



3
4
5
6
7
# File 'lib/react/validator.rb', line 3

def self.build(&block)
  validator = self.new
  validator.instance_eval(&block)
  validator
end

Instance Method Details

#default_propsObject



59
60
61
62
63
# File 'lib/react/validator.rb', line 59

def default_props
  @rules
  .select {|key, value| value.keys.include?("default") }
  .inject({}) {|memo, (k,v)| memo[k] = v[:default]; memo}
end

#optional(prop_name, options = {}) ⇒ Object



19
20
21
22
23
# File 'lib/react/validator.rb', line 19

def optional(prop_name, options = {})
  rule = options
  options[:required] = false
  @rules[prop_name] = options
end

#requires(prop_name, options = {}) ⇒ Object



13
14
15
16
17
# File 'lib/react/validator.rb', line 13

def requires(prop_name, options = {})
  rule = options
  options[:required] = true
  @rules[prop_name] = options
end

#validate(props) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/react/validator.rb', line 25

def validate(props)
  errors = []
  props.keys.each do |prop_name|
    errors <<  "Provided prop `#{prop_name}` not specified in spec"  if @rules[prop_name] == nil
  end

  props = props.select {|key| @rules.keys.include?(key) }

  # requires or not
  (@rules.keys - props.keys).each do |prop_name|
    errors << "Required prop `#{prop_name}` was not specified" if @rules[prop_name][:required]
  end

  # type
  props.each do |prop_name, value|
    if klass = @rules[prop_name][:type]
      if klass.is_a?(Array)
        errors <<  "Provided prop `#{prop_name}` was not an Array of the specified type `#{klass[0]}`" unless value.all?{ |ele| ele.is_a?(klass[0]) }
      else
        errors <<  "Provided prop `#{prop_name}` was not the specified type `#{klass}`" unless value.is_a?(klass)
      end
    end
  end

  # values
  props.each do |prop_name, value|
    if values = @rules[prop_name][:values]
      errors << "Value `#{value}` for prop `#{prop_name}` is not an allowed value" unless values.include?(value)
    end
  end

  errors
end