Class: MarkMapper::Plugins::Validations::UniquenessValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator


31
32
33
34
# File 'lib/mark_mapper/plugins/validations.rb', line 31

def initialize(options)
  @klass = options[:class] #only provided in ActiveModel 4.1 and higher
  super(options.reverse_merge(:case_sensitive => true))
end

Instance Method Details

#message(instance) ⇒ Object


66
67
68
# File 'lib/mark_mapper/plugins/validations.rb', line 66

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

#scope_conditions(instance) ⇒ Object


70
71
72
73
74
# File 'lib/mark_mapper/plugins/validations.rb', line 70

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

#setup(klass) ⇒ Object


39
40
41
# File 'lib/mark_mapper/plugins/validations.rb', line 39

def setup(klass)
  @klass = klass
end

#validate_each(record, attribute, value) ⇒ Object


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mark_mapper/plugins/validations.rb', line 44

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

  if options[:case_sensitive] == true
    conditions[attribute] = value
  else
    conditions[attribute] = {
      '$eq' => value.to_s.downcase,
      options: {
        case_sensitive: false
      }
    }
  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