Class: MongoMapper::Plugins::Validations::UniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- MongoMapper::Plugins::Validations::UniquenessValidator
- Defined in:
- lib/mongo_mapper/plugins/validations.rb
Instance Method Summary collapse
-
#initialize(options) ⇒ UniquenessValidator
constructor
A new instance of UniquenessValidator.
- #message(instance) ⇒ Object
- #scope_conditions(instance) ⇒ Object
- #setup(klass) ⇒ Object
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
31 32 33 |
# File 'lib/mongo_mapper/plugins/validations.rb', line 31 def initialize() super(.reverse_merge(:case_sensitive => true)) end |
Instance Method Details
#message(instance) ⇒ Object
56 57 58 |
# File 'lib/mongo_mapper/plugins/validations.rb', line 56 def (instance) super || "has already been taken" end |
#scope_conditions(instance) ⇒ Object
60 61 62 63 64 |
# File 'lib/mongo_mapper/plugins/validations.rb', line 60 def scope_conditions(instance) Array([:scope] || []).inject({}) do |conditions, key| conditions.merge(key => instance[key]) end end |
#setup(klass) ⇒ Object
35 36 37 |
# File 'lib/mongo_mapper/plugins/validations.rb', line 35 def setup(klass) @klass = klass end |
#validate_each(record, attribute, value) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/mongo_mapper/plugins/validations.rb', line 39 def validate_each(record, attribute, value) conditions = scope_conditions(record) if [: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, .except(:case_sensitive, :scope).merge(:value => value)) end end |