Sha256: cc1e43385e54e58c02cb471baff1a8414022ccfa9cbf0778540e79b3e4d06234
Contents?: true
Size: 1.24 KB
Versions: 1
Compression:
Stored size: 1.24 KB
Contents
module ExtraValidations # 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 # class CollectionLengthValidator < ActiveModel::EachValidator def check_validity! fail ArgumentError, ':in must be a Range' unless options[:in].is_a?(Range) end # @param record An object that has ActiveModel::Validations included # @param attribute [Symbol] # @param collection [Array] 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 end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
extra_validations-0.1.1 | lib/extra_validations/collection_length_validator.rb |