Class: SubsetValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_subset_validator/subset_validator.rb

Constant Summary collapse

ERROR_MESSAGE =
"An argument must be supplied for the :of option " <<
"of the configuration hash and must evaluate to an array or a set"

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/active_subset_validator/subset_validator.rb', line 5

def check_validity!
  if options[:of].respond_to?(:call)
    return
  elsif options[:of].is_a?(Array) || options[:of].is_a?(Set)
    unless ActiveSubsetValidator.is_a_set? options[:of]
      raise ArgumentError, ERROR_MESSAGE
    end
  else
    raise ArgumentError, ERROR_MESSAGE
  end
end

#validate_each(record, attribute, value) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/active_subset_validator/subset_validator.rb', line 17

def validate_each(record, attribute, value)
  message = options[:message] ? options[:message] : "is not a subset of the list"
  allow_nil = options[:allow_nil] === false ? false : true

  if options[:of].respond_to?(:call)
    superset = options[:of].call(record)
    unless ActiveSubsetValidator.is_a_set? superset
      raise ArgumentError, ERROR_MESSAGE
    end
  else
    superset = options[:of]
  end
  
  if value.nil?
    unless allow_nil
      record.errors[attribute] << "cannot be nil"
    end
  else
    unless ActiveSubsetValidator.set_difference(value, superset).empty?
      record.errors[attribute] << message
    end
  end
end