Class: Exocora::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/exocora/validation.rb

Overview

Validates a parameter. If a block is provided, the block is applied to values passed to apply; the return value determines if the value is valid. Otherwise, compares filter === value.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filter = Object, message = 'must be valid') ⇒ Validation

Returns a new instance of Validation.



9
10
11
12
13
# File 'lib/exocora/validation.rb', line 9

def initialize(filter = Object, message = 'must be valid')
  @filter = filter
  @message = message
  @negate = false
end

Instance Attribute Details

#filterObject

Returns the value of attribute filter.



7
8
9
# File 'lib/exocora/validation.rb', line 7

def filter
  @filter
end

#messageObject

Returns the value of attribute message.



7
8
9
# File 'lib/exocora/validation.rb', line 7

def message
  @message
end

#negateObject

Returns the value of attribute negate.



7
8
9
# File 'lib/exocora/validation.rb', line 7

def negate
  @negate
end

Instance Method Details

#because(message) ⇒ Object Also known as: explain

Change the message given when this validation fails.



16
17
18
19
# File 'lib/exocora/validation.rb', line 16

def because(message)
  @message = message
  self
end

#if(filter, &block) ⇒ Object Also known as: with, when

Sets the filter used



64
65
66
67
68
# File 'lib/exocora/validation.rb', line 64

def if(filter, &block)
  @filter = block_given? ? block : filter
  @negate = false
  self
end

#to_sObject



22
23
24
# File 'lib/exocora/validation.rb', line 22

def to_s
  "#{@message} #{@negate ? 'unless' : 'when'} #{@filter.inspect}"
end

#unless(filter, &block) ⇒ Object

Adds the opposite of this filter



27
28
29
30
31
# File 'lib/exocora/validation.rb', line 27

def unless(filter, &block)
  @filter = block_given? ? block : filter
  @negate = true
  self
end

#validate(value) ⇒ Object

Applies this validation to a valie. Returns true, or raises a ValidationError.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/exocora/validation.rb', line 35

def validate(value)
  # Treat the filter as a function or a rubric
  if @filter.respond_to? :call
    method = :call
  else
    method = :===
  end

  # Check the value
  begin
    result = @filter.send method, value
  rescue
    result = false
  end

  # If we're a negative filter, negate the result
  if negate
    result = ! result
  end

  # Return
  if result
    value
  else
    raise ValidationError.new(value, @message)
  end
end