Class: MongoModel::DocumentExtensions::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mongomodel/document/validations/uniqueness.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator



7
8
9
10
11
12
# File 'lib/mongomodel/document/validations/uniqueness.rb', line 7

def initialize(options)
  options = options.reverse_merge(:case_sensitive => true)
  
  ActiveSupport::Deprecation.silence { super }
  setup!(options[:class]) if options[:class] && !@klass
end

Instance Method Details

#setup(klass) ⇒ Object



14
15
16
# File 'lib/mongomodel/document/validations/uniqueness.rb', line 14

def setup(klass)
  setup!(klass)
end

#validate_each(record, attribute, value) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mongomodel/document/validations/uniqueness.rb', line 18

def validate_each(record, attribute, value)
  finder_class = find_finder_class_for(record)
  unique_scope = finder_class.scoped
  
  if options[:case_sensitive] || !value.is_a?(String)
    unique_scope = unique_scope.where(attribute => value)
  else
    unique_scope = unique_scope.where("_lowercase_#{attribute}" => value.downcase)
  end
  
  Array.wrap(options[:scope]).each do |scope|
    unique_scope = unique_scope.where(scope => record.send(scope))
  end
  
  unique_scope = unique_scope.where(:id.ne => record.id) unless record.new_record?
  
  if unique_scope.any?
    record.errors.add(attribute, :taken, :message => options[:message], :value => value)
  end
end