Sha256: f119cfd8b6872913576c904ed6956c6d736f42e50a743f438f01047856a4e884

Contents?: true

Size: 843 Bytes

Versions: 4

Compression:

Stored size: 843 Bytes

Contents

# Checks if the value of an attribute is equal to a value or proc result.
#
class EqualityValidator < ActiveModel::EachValidator
  # Checks if an attribute value is equal to a value or proc result.
  #
  # @param [Object] record object to validate
  # @param [String] attribute name of the object attribute to validate
  # @param [Object] value attribute value
  def validate_each(record, attribute, value)
    to = options[:to]

    reference_value = to.respond_to?(:call) ? options[:to].call(record) : to

    return if compare_value(value, reference_value)

    record.errors[attribute] << options.fetch(:message) do
      I18n.t(translation_key, value: reference_value)
    end
  end

  private

  def compare_value(value, reference_value)
    value == reference_value
  end

  def translation_key
    'errors.messages.equality'
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
missing_validators-2.3.0 lib/missing_validators/validators/equality_validator.rb
missing_validators-2.2.0 lib/missing_validators/validators/equality_validator.rb
missing_validators-2.1.0 lib/missing_validators/validators/equality_validator.rb
missing_validators-2.0.0 lib/missing_validators/validators/equality_validator.rb