Class: MongoMapper::Validations::ValidatesUniquenessOf

Inherits:
Validatable::ValidationBase
  • Object
show all
Defined in:
lib/mongo_mapper/validations.rb

Instance Method Summary collapse

Instance Method Details

#message(instance) ⇒ Object



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

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

#scope_conditions(instance) ⇒ Object



25
26
27
28
29
30
# File 'lib/mongo_mapper/validations.rb', line 25

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

#valid?(instance) ⇒ Boolean

Returns:



13
14
15
16
17
18
19
# File 'lib/mongo_mapper/validations.rb', line 13

def valid?(instance)
  value = instance[attribute]
  return true if allow_blank && value.blank?
  base_conditions = case_sensitive ? {self.attribute => value} : {}
  doc = instance.class.first(base_conditions.merge(scope_conditions(instance)).merge(where_conditions(instance)))
  doc.nil? || instance.id == doc.id
end

#where_conditions(instance) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/mongo_mapper/validations.rb', line 32

def where_conditions(instance)
  conditions = {}
  unless case_sensitive
    conditions.merge!({'$where' => "this.#{attribute}.toLowerCase() == '#{instance[attribute].downcase}'"})
  end
  conditions
end