Class: MongoMapper::Plugins::Validations::ValidatesUniquenessOf

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

Instance Method Summary collapse

Instance Method Details

#message(instance) ⇒ Object



38
39
40
# File 'lib/mongo_mapper/plugins/validations.rb', line 38

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

#scope_conditions(instance) ⇒ Object



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

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

#valid?(instance) ⇒ Boolean

Returns:



29
30
31
32
33
34
35
36
# File 'lib/mongo_mapper/plugins/validations.rb', line 29

def valid?(instance)
  value = instance[attribute]
  return true if allow_blank && value.blank?
  return true if allow_nil && value.nil?
  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



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

def where_conditions(instance)
  conditions = {}
  conditions[attribute] = /#{instance[attribute].to_s}/i unless case_sensitive
  conditions
end