Sha256: 46a86ff75766a02cbde472b57da0b580562373414d10a9df4f689ec00e4304a0

Contents?: true

Size: 601 Bytes

Versions: 1

Compression:

Stored size: 601 Bytes

Contents

module ExtraValidations
  class CollectionLengthValidator < ActiveModel::EachValidator
    def check_validity!
      unless options[:in].is_a?(Range)
        fail ArgumentError, ':in must be a Range'
      end
    end

    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.0 lib/extra_validations/collection_length_validator.rb