Class: RestrictToValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- RestrictToValidator
- 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
- #allowed_options(record) ⇒ Object
- #allowed_options_string(record) ⇒ Object
- #check_validity! ⇒ Object
-
#initialize(*args) ⇒ RestrictToValidator
constructor
A new instance of RestrictToValidator.
- #validate_each(record, attribute, value) ⇒ Object
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 = [:allowed_options] end |
Instance Method Details
#allowed_options(record) ⇒ Object
16 17 18 |
# File 'lib/activemodel-validators/restrict_to_validator.rb', line 16 def (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 (record) = (record) if .is_a?(Range) "#{}" else .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| [: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) = (record) inclusion_method = inclusion_method() unless .send(inclusion_method, value) record.errors.add(attribute, :restrict_to, .except(:in).merge!( value: value, allowed_options: (record) ) ) end end |