Class: DataMapper::Validate::ContextualValidators

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/dm-validations/contextual_validators.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContextualValidators

Returns a new instance of ContextualValidators.

Since:

  • 0.9



22
23
24
# File 'lib/dm-validations/contextual_validators.rb', line 22

def initialize
  @contexts = {}
end

Instance Attribute Details

#contextsObject (readonly)

Since:

  • 0.9



20
21
22
# File 'lib/dm-validations/contextual_validators.rb', line 20

def contexts
  @contexts
end

Instance Method Details

#clear!Object

Clear all named context validators off of the resource

Since:

  • 0.9



49
50
51
# File 'lib/dm-validations/contextual_validators.rb', line 49

def clear!
  contexts.clear
end

#context(name) ⇒ Array<DataMapper::Validate::GenericValidator>

Return an array of validators for a named context

Parameters:

  • Context (String)

    name for which return validators

Returns:

Since:

  • 0.9



43
44
45
# File 'lib/dm-validations/contextual_validators.rb', line 43

def context(name)
  contexts[name] ||= []
end

#dumpObject Also known as: inspect

API

Since:

  • 0.9



30
31
32
33
34
# File 'lib/dm-validations/contextual_validators.rb', line 30

def dump
  contexts.each_pair do |key, context|
    puts "Key=#{key} Context: #{context}"
  end
end

#execute(named_context, target) ⇒ Boolean

Execute all validators in the named context against the target

Parameters:

  • named_context (Symbol)

    the context we are validating against

  • target (Object)

    the resource that we are validating

Returns:

  • (Boolean)

    true if all are valid, otherwise false

Raises:

  • (ArgumentError)

Since:

  • 0.9



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/dm-validations/contextual_validators.rb', line 61

def execute(named_context, target)
  raise(ArgumentError, "validation context #{named_context} doesn't seem to be defined. Known contexts are #{contexts.keys.inspect}") if !named_context || (contexts.length > 0 && !contexts[named_context])
  target.errors.clear!
  result = true
  # note that all? and any? stop iteration on first negative or positive result,
  # so we really have to use each here to make sure all validators are
  # executed
  context(named_context).select { |validator| validator.execute?(target) }.each do |validator|
    result = false unless validator.call(target)
  end


  result
end