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.

Direct Known Subclasses

ValidationOfPresence

Constant Summary collapse

DEFAULT_MESSAGE =
'must be present'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filter = Object, message = DEFAULT_MESSAGE) ⇒ Validation

Returns a new instance of Validation.



11
12
13
14
15
# File 'lib/exocora/validation.rb', line 11

def initialize(filter=Object, message=DEFAULT_MESSAGE)
  @filter = filter
  @message = message
  @negate = false
end

Instance Attribute Details

#filterObject

Returns the value of attribute filter.



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

def filter
  @filter
end

#messageObject

Returns the value of attribute message.



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

def message
  @message
end

#negateObject

Returns the value of attribute negate.



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

def negate
  @negate
end

Instance Method Details

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

Change the message given when this validation fails.



18
19
20
21
# File 'lib/exocora/validation.rb', line 18

def because(message)
  @message = message
  self
end

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

Sets the filter used



66
67
68
69
70
# File 'lib/exocora/validation.rb', line 66

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

#to_sObject



24
25
26
# File 'lib/exocora/validation.rb', line 24

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

#unless(filter, &block) ⇒ Object

Adds the opposite of this filter



29
30
31
32
33
# File 'lib/exocora/validation.rb', line 29

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.



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
62
63
# File 'lib/exocora/validation.rb', line 37

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