Sha256: c07be362edc66a765f7c32b7bed4a1fb75eddc52fade27a299766ce37ee2aca3

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

module ExtraValidations
  # Makes sure that an object/record exists.
  #
  # Suppose that you have the following class:
  #
  #   class Book
  #     include ActiveModel::Model
  #     include ExtraValidations
  #
  #     attr_accessor :author_id
  #
  #     validates :author_id, existence: -> (id) { Author.exists?(id) }
  #   end
  #
  # This validator will execute the given block and, if it returns false, the
  # object will not be valid:
  #
  #   book = Book.new
  #   book.author_id = 100
  #   book.valid? # => false
  #
  #   book.author_id = Author.first.id
  #   book.valid? # => true
  #
  class ExistenceValidator < ActiveModel::EachValidator
    def check_validity!
      unless options[:with].is_a?(Proc)
        fail ArgumentError, ':with must be a Proc'
      end
    end

    # @param record An object that has ActiveModel::Validations included
    # @param attribute [Symbol]
    # @param id [Integer]
    def validate_each(record, attribute, id)
      return if id.blank?

      success = options[:with].call(id)
      record.errors.add(attribute, :not_found) unless success
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
extra_validations-0.1.1 lib/extra_validations/existence_validator.rb