Class: Correlate::Validator

Inherits:
CouchRest::Validation::GenericValidator
  • Object
show all
Defined in:
lib/correlate/validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(field_name, options = {}) ⇒ Validator

Returns a new instance of Validator.



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

def initialize( field_name, options = {} )
  super
  @field_name, @options = field_name, options
end

Instance Method Details

#call(target) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/correlate/validator.rb', line 9

def call( target )
  results = []

  target.class.correlations.each do |correlation|
    case correlation.type
    when :some
      results << validate_some( correlation, target )
    when :a
      results << validate_a( correlation, target )
    end
  end

  !results.any? { |r| r == false }
end

#validate_a(correlation, target) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/correlate/validator.rb', line 38

def validate_a( correlation, target )
  results = true

  if correlation.required && target.send( correlation.name ).nil?
    target.errors.add( correlation.name, "is required" )
    results = false
  end

  results
end

#validate_some(correlation, target) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/correlate/validator.rb', line 24

def validate_some( correlation, target )
  results = true

  case correlation.requires
  when Fixnum
    unless target.send( correlation.name, true ).size >= correlation.requires
      target.errors.add( correlation.name, "Requires at least #{correlation.requires} #{correlation.name}" )
      results = false
    end
  end

  results
end