Class: DataMapper::Validations::UniqueValidator

Inherits:
GenericValidator show all
Defined in:
lib/data_mapper/validations/unique_validator.rb

Constant Summary collapse

ERROR_MESSAGES =
{
  :unique => '#{field} has already been taken'
}

Instance Method Summary collapse

Methods inherited from GenericValidator

#add_error, #validation_error_message

Constructor Details

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

Returns a new instance of UniqueValidator.



10
11
12
13
# File 'lib/data_mapper/validations/unique_validator.rb', line 10

def initialize(field_name, options = {})
  @options = options
  @field_name = field_name.to_sym
end

Instance Method Details

#call(target) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/data_mapper/validations/unique_validator.rb', line 15

def call(target)
  field = Inflector.humanize(@field_name)

  unless valid?(target)
    error_message = validation_error_message(ERROR_MESSAGES[:unique], nil, binding)        
    add_error(target, error_message , @field_name)
    return false
  end
  
  return true
end

#valid?(target) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/data_mapper/validations/unique_validator.rb', line 27

def valid?(target)
  field_value = target.instance_variable_get("@#{@field_name}")
  return true if @options[:allow_nil] && field_value.nil?
  
  finder_options = { @field_name => field_value }
  
  if @options[:scope]
    scope_value = target.instance_variable_get("@#{@options[:scope]}")
    finder_options.merge! @options[:scope] => scope_value
  end
  
  finder_options.merge!({ target.session.mappings[target.class].key.name.not => target.key }) unless target.new_record?
  
  target.session.first(target.class, finder_options).nil?
end