Sha256: c9c0caed3c6d4c79b44f0b4c4b057f79edf568a64cb46f9d39ea3e85a8cf0c0f

Contents?: true

Size: 1.05 KB

Versions: 56

Compression:

Stored size: 1.05 KB

Contents

class RelationLengthValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if smaller?(value)
      record.errors.add(attribute, smaller_error_message, options)
    elsif greater?(value)
      record.errors.add(attribute, greater_error_message, options)
    end
  end

  private

  def minimum
    options[:minimum] || 0
  end

  def maximum
    options[:maximum] || Float::INFINITY
  end

  def smaller?(value)
    value.length < minimum
  end

  def greater?(value)
    value.length > minimum
  end

  def smaller_error_message
    message = options[:message] && options[:message][:minimum]
    message || ::I18n.t(
      "activerecord.errors.relation_length_is_smaller",
      minimum: minimum,
      default: "must have at least #{ minimum } elements"
    )
  end

  def greater_error_message
    message = options[:message] && options[:message][:maximum]
    message || ::I18n.t(
      "activerecord.errors.relation_length_is_greater",
      maximum: maximum,
      default: "must have at most #{ maximum } elements"
    )
  end
end

Version data entries

56 entries across 56 versions & 1 rubygems

Version Path
para-0.12.4 lib/rails/relation_length_validator.rb
para-0.12.3 lib/rails/relation_length_validator.rb
para-0.12.2 lib/rails/relation_length_validator.rb
para-0.12.1 lib/rails/relation_length_validator.rb
para-0.12.0 lib/rails/relation_length_validator.rb
para-0.11.4 lib/rails/relation_length_validator.rb
para-0.11.3 lib/rails/relation_length_validator.rb
para-0.11.2 lib/rails/relation_length_validator.rb
para-0.11.1 lib/rails/relation_length_validator.rb
para-0.11.0 lib/rails/relation_length_validator.rb
para-0.10.0 lib/rails/relation_length_validator.rb
para-0.9.4 lib/rails/relation_length_validator.rb
para-0.9.3.3 lib/rails/relation_length_validator.rb
para-0.9.3.2 lib/rails/relation_length_validator.rb
para-0.9.3.1 lib/rails/relation_length_validator.rb
para-0.9.2 lib/rails/relation_length_validator.rb
para-0.9.0 lib/rails/relation_length_validator.rb
para-0.8.15 lib/rails/relation_length_validator.rb
para-0.8.14 lib/rails/relation_length_validator.rb
para-0.8.13 lib/rails/relation_length_validator.rb