Class: MongoMapper::Plugins::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mongo_mapper/plugins/validations.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator.



20
21
22
# File 'lib/mongo_mapper/plugins/validations.rb', line 20

def initialize(options)
  super(options.reverse_merge(:case_sensitive => true))
end

Instance Method Details

#message(instance) ⇒ Object



45
46
47
# File 'lib/mongo_mapper/plugins/validations.rb', line 45

def message(instance)
  super || "has already been taken"
end

#scope_conditions(instance) ⇒ Object



49
50
51
52
53
# File 'lib/mongo_mapper/plugins/validations.rb', line 49

def scope_conditions(instance)
  Array(options[:scope] || []).inject({}) do |conditions, key|
    conditions.merge(key => instance[key])
  end
end

#setup(klass) ⇒ Object



24
25
26
# File 'lib/mongo_mapper/plugins/validations.rb', line 24

def setup(klass)
  @klass = klass
end

#validate_each(record, attribute, value) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mongo_mapper/plugins/validations.rb', line 28

def validate_each(record, attribute, value)
  conditions = scope_conditions(record)

  if options[:case_sensitive]
    conditions[attribute] = value
  else
    conditions[attribute] = /^#{Regexp.escape(value.to_s)}$/i
  end

  # Make sure we're not including the current document in the query
  conditions[:_id.ne] = record._id if record._id

  if @klass.exists?(conditions)
    record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
  end
end