Class: Garcon::SafeTaskExecutor

Inherits:
Object
  • Object
show all
Defined in:
lib/garcon/task/safe_task_executor.rb

Overview

A simple utility class that executes a callable and returns and array of three elements:

  • success: indicating if the callable has been executed without errors

  • value: filled by the callable result if it has been executed without

    errors, nil otherwise
    
  • reason: the error risen by the callable if it has been executed with

    errors, nil otherwise
    

Instance Method Summary collapse

Constructor Details

#initialize(task, opts = {}) ⇒ SafeTaskExecutor

Returns a new instance of SafeTaskExecutor.



34
35
36
37
38
# File 'lib/garcon/task/safe_task_executor.rb', line 34

def initialize(task, opts = {})
  @task  = task
  @mutex = Mutex.new
  @ex    = opts.fetch(:rescue_exception, false) ? Exception : StandardError
end

Instance Method Details

#execute(*args) ⇒ Array

Returns:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/garcon/task/safe_task_executor.rb', line 41

def execute(*args)
  @mutex.synchronize do
    success = false
    value   = reason = nil

    begin
      value    =  @task.call(*args)
      success  =  true
    rescue @ex => e
      reason   =  e
      success  =  false
    end

    [success, value, reason]
  end
end