Class: RestrictToValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/activemodel-validators/restrict_to_validator.rb

Constant Summary collapse

ErrorMessage =
"An object with the method #include? or a proc or lambda is required, " <<
"and must be supplied as the :allowed_options option of the configuration hash"

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ RestrictToValidator

Returns a new instance of RestrictToValidator.



5
6
7
8
# File 'lib/activemodel-validators/restrict_to_validator.rb', line 5

def initialize(*args)
  super
  @allowed_options = options[:allowed_options]
end

Instance Method Details

#allowed_options(record) ⇒ Object



16
17
18
# File 'lib/activemodel-validators/restrict_to_validator.rb', line 16

def allowed_options(record)
  @allowed_options.respond_to?(:call) ? @allowed_options.call(record) : @allowed_options
end

#allowed_options_string(record) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/activemodel-validators/restrict_to_validator.rb', line 19

def allowed_options_string(record)
  allowed_options = allowed_options(record)
  if allowed_options.is_a?(Range)
    "#{allowed_options}"
  else
    allowed_options.to_sentence(last_word_connector: ', or ')
  end
end

#check_validity!Object



10
11
12
13
14
# File 'lib/activemodel-validators/restrict_to_validator.rb', line 10

def check_validity!
  unless [:include?, :call].any?{ |method| options[:allowed_options].respond_to?(method) }
    raise ArgumentError, ErrorMessage
  end
end

#validate_each(record, attribute, value) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/activemodel-validators/restrict_to_validator.rb', line 28

def validate_each(record, attribute, value)
  allowed_options = allowed_options(record)
  inclusion_method = inclusion_method(allowed_options)
  unless allowed_options.send(inclusion_method, value)
    record.errors.add(attribute, :restrict_to,
                      options.except(:in).merge!(
                        value: value,
                        allowed_options: allowed_options_string(record)
                      )
    )
  end
end