Module: Validation::Rules

Included in:
Validator
Defined in:
lib/validation/validator.rb

Instance Method Summary collapse

Instance Method Details

#errorsObject

A hash of errors for this object



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

def errors
  @errors ||= {}
end

#rule(field, rule) ⇒ Object

Define a rule for this object

The rule parameter can be one of the following:

  • a symbol that matches to a class in the Validation::Rule namespace

  • e.g. rule(:field, :not_empty)

  • a hash containing the rule as the key and it’s parameters as the values

  • e.g. rule(:field, :length => => 3, :maximum => 5)

  • an array combining the two previous types



22
23
24
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
# File 'lib/validation/validator.rb', line 22

def rule(field, rule)
  field = field.to_sym
  if rules[field].nil?
    rules[field] = []
  end

  begin
    if rule.respond_to?(:each_pair)
      add_parameterized_rule(field, rule)
    elsif rule.respond_to?(:each)
      rule.each do |r|
        if r.respond_to?(:each_pair)
          add_parameterized_rule(field, r)
        else
          r = Validation::Rule.const_get(camelize(r)).new
          add_object_to_rule(r)
          rules[field] << r
        end
      end
    else
      rule = Validation::Rule.const_get(camelize(rule)).new
      add_object_to_rule(rule)
      rules[field] << rule
    end
  rescue NameError => e
    raise InvalidRule.new(e)
  end
end

#rulesObject

A hash of rules for this object



4
5
6
# File 'lib/validation/validator.rb', line 4

def rules
  @rules ||= {}
end

#valid?Boolean

Determines if this object is valid. When a rule fails for a field, this will stop processing further rules. In this way, you’ll only get one error per field

Returns:

  • (Boolean)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/validation/validator.rb', line 54

def valid?
  valid = true

  rules.each_pair do |field, rules|
    if ! @obj.respond_to?(field)
      raise InvalidKey
    end

    rules.each do |r|
      if ! r.valid_value?(@obj.send(field))
        valid = false
        errors[field] = {:rule => r.error_key, :params => r.params}
        break
      end
    end
  end

  @valid = valid
end