Sha256: adfe3341a9ad4543e3f4021d515b241cb21bd863f84a439baa79147bfdce0c53

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

# Allows to check if the value of a specific attribute is not equal to
# the value of another attribute of an object.
#
# @example Validate that flight origin is not the same as its destination.
#   class Flight << ActiveRecord::Base
#     attr_accessor :origin, :destination
#     validates :origin, inequality: { to: :destination }
#   end
class InequalityValidator < ActiveModel::EachValidator
  # Checks if an attribute value is unequal to another attrubute value.
  #
  # @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)
    unequal_to = options[:to]

    unequal_to_value = if unequal_to.respond_to?(:call)
      options[:to].call(record)
    else
      record.send(unequal_to.to_sym)
    end

    if unequal_to.present? && value == unequal_to_value
      message = options[:message] || I18n.t('errors.messages.inequality', attr: unequal_to)
      record.errors[attribute] << message
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
missing_validators-1.1.0 lib/missing_validators/validators/inequality_validator.rb