Class: SimpleMaster::Master::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/simple_master/master/validatable.rb

Overview

Validator works similar to ActiveRecord::Validations::UniquenessValidator.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

:nodoc:



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/simple_master/master/validatable.rb', line 19

def initialize(options)
  if options[:conditions] && !options[:conditions].respond_to?(:call)
    fail ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \
                        "Pass a callable instead: `conditions: -> { where(approved: true) }`"
  end
  unless Array(options[:scope]).all? { |scope| scope.respond_to?(:to_sym) }
    fail ArgumentError, "#{options[:scope]} is not supported format for :scope option. " \
                        "Pass a symbol or an array of symbols instead: `scope: :user_id`"
  end
  super
  @klass = options[:class]
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/simple_master/master/validatable.rb', line 32

def validate_each(record, attribute, value)
  unless @klass.select { _1.send(attribute) == value }.one?
    error_options = options.except(:case_sensitive, :scope, :conditions)
    error_options[:value] = value

    record.errors.add(attribute, :taken, **error_options)
  end
end