Sha256: e168efd5cfe1f9d849d8ea1e2524b8177964990d16597a89770dbffe9949e487

Contents?: true

Size: 926 Bytes

Versions: 1

Compression:

Stored size: 926 Bytes

Contents

class EqualityValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    to = options.fetch(:to, nil)
    if to.nil?
      raise ArgumentError,
        "ArgumentError: missing ':to' attribute for comparison."
    end

    operator = options.fetch(:operator, nil)
    operators = OPERATORS.keys
    unless operators.include?(operator)
      raise ArgumentError,
        "Unknown operator: #{operator.inspect}. Valid operators are: #{operators.map(&:inspect).join(", ")}"
    end
    operator = OPERATORS.fetch(operator)

    unless value.send(operator, record.send(to))
      record.errors[attribute] << options.fetch(:message, I18n.t("active_validation.errors.messages.equality", attr: to, operator: operator))
    end
  end

  private

  OPERATORS = {
    less_than: :<, less_than_or_equal_to: :<=, greater_than: :>,
    greater_than_or_equal_to: :>=, equal_to: :==, not_equal_to: :!=
  }

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_validation-3.0.0 lib/active_validation/validators/equality_validator.rb