Class: Cuprum::Function

Inherits:
Object
  • Object
show all
Defined in:
lib/cuprum/function.rb

Overview

Functional object that encapsulates a business logic operation with a consistent interface and tracking of result value and status.

A Function can be defined either by passing a block to the constructor, or by defining a subclass of Function and implementing the #process method.

Examples:

A Function with a block

double_function = Function.new { |int| 2 * int }
result          = double_function.call(5)

result.value #=> 10

A Function subclass

class MultiplyFunction
  def initialize multiplier
    @multiplier = multiplier
  end # constructor

  private

  def process int
    int * @multiplier
  end # method process
end # class

triple_function = MultiplyFunction.new(3)
result          = triple_function.call(5)

result.value #=> 15

A Function with errors

class DivideFunction
  def initialize divisor
    @divisor = divisor
  end # constructor

  private

  def process int
    if @divisor.zero?
      errors << 'errors.messages.divide_by_zero'

      return
    end # if

    int / @divisor
  end # method process
end # class

halve_function = DivideFunction.new(2)
result         = halve_function.call(10)

result.errors #=> []
result.value  #=> 5

function_with_errors = DivideFunction.new(0)
result               = function_with_errors.call(10)

result.errors #=> ['errors.messages.divide_by_zero']
result.value  #=> nil

Direct Known Subclasses

Operation

Defined Under Namespace

Classes: NotImplementedError

Instance Method Summary collapse

Constructor Details

#initialize {|*arguments, **keywords, &block| ... } ⇒ Function

Returns a new instance of Cuprum::Function.

Yields:

  • (*arguments, **keywords, &block)

    If a block is given, the #call method will wrap the block and set the result #value to the return value of the block. This overrides the implementation in #process, if any.



82
83
84
# File 'lib/cuprum/function.rb', line 82

def initialize &implementation
  define_singleton_method :process, &implementation if implementation
end

Instance Method Details

#call(*arguments, *keywords) { ... } ⇒ Cuprum::Result

Executes the logic encoded in the constructor block, or the #process method if no block was passed to the constructor.

Parameters:

  • arguments (Array)

    Arguments to be passed to the implementation.

  • keywords (Hash)

    Keywords to be passed to the implementation.

Yields:

  • If a block argument is given, it will be passed to the implementation.

Returns:

Raises:

  • (NotImplementedError)

    unless a block was passed to the constructor or the #process method was overriden by a Function subclass.



102
103
104
105
106
107
108
109
110
# File 'lib/cuprum/function.rb', line 102

def call *args, &block
  Cuprum::Result.new.tap do |result|
    @errors = result.errors

    result.value = process(*args, &block)

    @errors = nil
  end # tap
end