Class: DataMapper::Validate::ConfirmationValidator

Inherits:
GenericValidator show all
Defined in:
lib/dm-validations/confirmation_validator.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Instance Attribute Summary

Attributes inherited from GenericValidator

#if_clause, #unless_clause

Instance Method Summary collapse

Methods inherited from GenericValidator

#==, #add_error, #execute?, #field_name

Constructor Details

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

Returns a new instance of ConfirmationValidator.

Since:

  • 0.9


10
11
12
13
14
15
# File 'lib/dm-validations/confirmation_validator.rb', line 10

def initialize(field_name, options = {})
  super
  @options = options
  @field_name, @confirm_field_name = field_name, (options[:confirm] || "#{field_name}_confirmation").to_sym
  @options[:allow_nil] = true unless @options.has_key?(:allow_nil)
end

Instance Method Details

#call(target) ⇒ Object

Since:

  • 0.9


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

def call(target)
  unless valid?(target)
    error_message = @options[:message] || '%s does not match the confirmation'.t(Extlib::Inflection.humanize(@field_name))
    add_error(target, error_message , @field_name)
    return false
  end

  return true
end

#valid?(target) ⇒ Boolean

Returns:

  • (Boolean)

Since:

  • 0.9


27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/dm-validations/confirmation_validator.rb', line 27

def valid?(target)
  field_value = target.instance_variable_get("@#{@field_name}")
  return true if @options[:allow_nil] && field_value.nil?
  return false if !@options[:allow_nil] && field_value.nil?

  if target.class.properties.has_property?(@field_name)
    return true unless target.attribute_dirty?(@field_name)
  end

  confirm_value = target.instance_variable_get("@#{@confirm_field_name}")
  field_value == confirm_value
end