Class: Neo4j::Rails::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/neo4j/rails/validations/uniqueness.rb

Instance Method Summary (collapse)

Constructor Details

- (UniquenessValidator) initialize(options)

A new instance of UniquenessValidator



7
8
9
10
# File 'lib/neo4j/rails/validations/uniqueness.rb', line 7

def initialize(options)
  super(options.reverse_merge(:case_sensitive => true))
    @validator =  options[:case_sensitive].nil? || options[:case_sensitive] ? ExactMatchValidator : FulltextMatchValidator
end

Instance Method Details

- (Object) index_error_message(klass, attribute, index_type)



20
21
22
# File 'lib/neo4j/rails/validations/uniqueness.rb', line 20

def index_error_message(klass,attribute,index_type)
  "Can't validate property #{attribute.inspect} on class #{klass} since there is no :#{index_type} lucene index on that property or the index declaration #{attribute} comes after the validation declaration in #{klass} (try to move it before the validation rules)"
end

- (Object) setup(klass)



12
13
14
15
16
17
18
# File 'lib/neo4j/rails/validations/uniqueness.rb', line 12

def setup(klass)
  @attributes.each do |attribute|
    if klass.index_type(attribute) != @validator.index_type
      raise index_error_message(klass,attribute,@validator.index_type)
    end
  end
end

- (Object) validate_each(record, attribute, value)



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/neo4j/rails/validations/uniqueness.rb', line 24

def validate_each(record, attribute, value)
  return if options[:allow_blank] && value.blank?
  @validator.query(record.class,attribute,value).each do |rec|
    if rec.id != record.id # it doesn't count if we find ourself!
      if @validator.match(rec, attribute, value)
        record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
      end
      break
    end
  end
end