Class: DataMapper::Validations::UniquenessValidator

Inherits:
GenericValidator show all
Includes:
Assertions
Defined in:
lib/dm-validations/validators/uniqueness_validator.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Instance Attribute Summary

Attributes inherited from GenericValidator

#field_name, #humanized_field_name, #if_clause, #options, #unless_clause

Instance Method Summary collapse

Methods inherited from GenericValidator

#==, #add_error, #allow_blank?, #allow_nil?, #execute?, #inspect, #optional?, #set_optional_by_default

Constructor Details

#initialize(field_name, options = {}) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator.

Since:

  • 0.9



11
12
13
14
15
16
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 11

def initialize(field_name, options = {})
  assert_kind_of 'scope', options[:scope], Array, Symbol if options.has_key?(:scope)
  super

  set_optional_by_default
end

Instance Method Details

#call(target) ⇒ Object

Since:

  • 0.9



18
19
20
21
22
23
24
25
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 18

def call(target)
  return true if valid?(target)

  error_message = @options[:message] || ValidationErrors.default_error_message(:taken, field_name)
  add_error(target, error_message, field_name)

  false
end

#valid?(target) ⇒ Boolean

Returns:

  • (Boolean)

Since:

  • 0.9



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 27

def valid?(target)
  value = target.validation_property_value(field_name)
  return true if optional?(value)

  opts = {
    :fields    => target.model.key,
    field_name => value,
  }

  Array(@options[:scope]).each { |subject| opts[subject] = target.__send__(subject) }

  resource = DataMapper.repository(target.repository.name) { target.model.first(opts) }

  return true if resource.nil?

  target.saved? && resource.key == target.key
end