Class: Mongoid::Validatable::UniquenessValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid-encrypted-fields/mongoid4/validatable/uniqueness.rb

Overview

Monkey-patch for Mongoid’s uniqueness validator to enforce that the :case_sensitive option does not work for encrypted fields; they must always be case-sensitive. Patch is confirmed to work on Mongoid >= 4.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ UniquenessValidator

Older versions of Mongoid’s UniquenessValidator have a klass variable to reference the validating document This was later replaced in ActiveModel with options



14
15
16
17
# File 'lib/mongoid-encrypted-fields/mongoid4/validatable/uniqueness.rb', line 14

def initialize(options={})
  @klass = options[:class] if options.key?(:class)
  super
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



10
11
12
# File 'lib/mongoid-encrypted-fields/mongoid4/validatable/uniqueness.rb', line 10

def klass
  @klass
end

Instance Method Details

#check_validity!Object



23
24
25
26
27
28
29
30
# File 'lib/mongoid-encrypted-fields/mongoid4/validatable/uniqueness.rb', line 23

def check_validity!
  return if case_sensitive?
  return unless klass
  attributes.each do |attribute|
    field_type = klass.fields[klass.database_field_name(attribute)].options[:type]
    raise ArgumentError, "Encrypted field :#{attribute} cannot support case insensitive uniqueness" if field_type.method_defined?(:encrypted)
  end
end

#setup(klass) ⇒ Object



19
20
21
# File 'lib/mongoid-encrypted-fields/mongoid4/validatable/uniqueness.rb', line 19

def setup(klass)
  @klass = klass
end