Class: React::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/react/opal/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/opal/validator.rb', line 9

def initialize
  @rules = {}
end

Class Method Details

.build(&block) ⇒ Object



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

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

Instance Method Details

#default_propsObject



63
64
65
66
67
# File 'lib/react/opal/validator.rb', line 63

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

#evaluate_more_rules(&block) ⇒ Object



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

def evaluate_more_rules(&block)
   self.instance_eval(&block)
end

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



23
24
25
26
27
# File 'lib/react/opal/validator.rb', line 23

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

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



17
18
19
20
21
# File 'lib/react/opal/validator.rb', line 17

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

#validate(props) ⇒ Object



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
58
59
60
61
# File 'lib/react/opal/validator.rb', line 29

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