Class: Monadic::Validation

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

Overview

Conducts several function calls which do checks, of which each must return Success or Failure and returns a list of all failures. Validation is not a monad, but an deemed an applicative functor

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeValidation

Returns a new instance of Validation.


11
12
13
# File 'lib/monadic/validation.rb', line 11

def initialize
  @result = []
end

Class Method Details

.fill(obj, params, validator) ⇒ Object

Useful to populate a data structure like a Struct, which takes values in its constructor


34
35
36
37
38
39
40
41
42
43
# File 'lib/monadic/validation.rb', line 34

def self.fill(obj, params, validator)
  properties = validator.methods - Module.methods
  values = properties.collect {|property| validator.send(property, params) }

  if values.all?(&:success?)
    Success(obj.new(*values.collect(&:fetch)))
  else
    Failure(obj.new(*values))
  end
end

Instance Method Details

#call(&block) ⇒ Object


15
16
17
18
19
20
21
22
23
# File 'lib/monadic/validation.rb', line 15

def call(&block)
  instance_eval(&block)

  if @result.any?(&:failure?)
    Failure(@result.select(&:failure?).map(&:fetch))
  else
    Success(@result.select(&:success?).map(&:fetch))
  end
end

#check(proc = nil, &block) ⇒ Object

Raises:


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

def check(proc=nil, &block)
  result = (proc || block).call
  raise NotEitherError, "Expected #{result.inspect} to be an Either" unless result.is_a? Either
  # @failure.fetch << result.fetch) if result.failure?
  @result << result
end