Class: ExtraValidations::CollectionLengthValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/extra_validations/collection_length_validator.rb

Overview

Validates the length of a collection.

Suppose that you have the following class:

class Book
  include ActiveModel::Model
  include ExtraValidations

  attr_accessor :authors

  validates :authors, collection_length: 1..5
end

This validator will make sure that the authors array will have at least 1 item and at most 5 items:

book = Book.new
book.authors = []
book.valid? # => false

book.authors = [Author.new]
book.valid? # => true

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



26
27
28
# File 'lib/extra_validations/collection_length_validator.rb', line 26

def check_validity!
  fail ArgumentError, ':in must be a Range' unless options[:in].is_a?(Range)
end

#validate_each(record, attribute, collection) ⇒ Object

Parameters:

  • record

    An object that has ActiveModel::Validations included

  • attribute (Symbol)
  • collection (Array)


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/extra_validations/collection_length_validator.rb', line 33

def validate_each(record, attribute, collection)
  min = options[:in].begin
  max = options[:in].end

  if collection.blank? || collection.length < min
    record.errors.add(attribute, :too_few, count: min)
  end

  if collection.present? && collection.length > max
    record.errors.add(attribute, :too_many, count: max)
  end
end