Module: Semi

Defined in:
lib/semi/config.rb,
lib/semi/driver.rb,
lib/semi/version.rb,
lib/semi/validate.rb,
lib/semi/variable.rb,
lib/semi/variables/base.rb

Defined Under Namespace

Modules: Variable, Variables Classes: Config, Driver, ValidationError, VariableError

Class Method Summary collapse

Class Method Details

.validate(value, rules) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/semi/validate.rb', line 6

def validate(value, rules)
  if rules.class == String
    rules = rules.split(/,\s?/)
  end
  # build a checklist for rules that match
  tests = Hash[ rules.collect { |r| [r, false] } ]

  tests.keys.each do |rule|
    case rule
    when 'required'
      tests[rule] = true unless value.nil?
    when 'integer'
      tests[rule] = Semi::Variables::Integer.validate(value)
    when 'string'
      tests[rule] = Semi::Variables::String.validate(value)
    when 'boolean'
      tests[rule] = Semi::Variables::Boolean.validate(value)
    when 'path'
      tests[rule] = Semi::Variables::Path.validate(value)
    when 'url'
      tests[rule] = Semi::Variables::Url.validate(value)
    end

    # test for regular expression
    if rule.start_with?('/') and rule.end_with?('/')
      re = Regexp.new(rule[1..-2])
      tests[rule] = true if re.match(value.to_s)
    end
  end

  failures = tests.each_pair.map { |r,t| r if not t }.compact
  unless failures.empty?
    raise ValidationError, "#{value}(#{value.class}) does not validate against #{failures} rules"
  end
end