Class: Neo4j::ActiveNode::Validations::UniquenessValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator.



24
25
26
# File 'lib/neo4j/active_node/validations.rb', line 24

def initialize(options)
  super(options.reverse_merge(case_sensitive: true))
end

Instance Method Details

#found(record, attribute, value) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/neo4j/active_node/validations.rb', line 34

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

  # TODO: Added as find(:name => nil) throws error
  value = '' if value.nil?

  conditions[attribute] = options[:case_sensitive] ? value : /#{Regexp.escape(value.to_s)}/i

  found = record.class.as(:result).where(conditions)
  found = found.where_not(neo_id: record.neo_id) if record._persisted_obj
  found
end

#message(instance) ⇒ Object



47
48
49
# File 'lib/neo4j/active_node/validations.rb', line 47

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

#scope_conditions(instance) ⇒ Object



51
52
53
54
55
# File 'lib/neo4j/active_node/validations.rb', line 51

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

#validate_each(record, attribute, value) ⇒ Object



28
29
30
31
32
# File 'lib/neo4j/active_node/validations.rb', line 28

def validate_each(record, attribute, value)
  return unless found(record, attribute, value).exists?

  record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(value: value))
end