Class: Karafka::Web::Ui::Lib::SafeRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/karafka/web/ui/lib/safe_runner.rb

Overview

Class used to execute code that can fail but we do not want to fail the whole operation. The primary use-case is for displaying deserialized data. We always need to assume, that part of the data can be corrupted and it should not crash the whole UI.

It caches the result and does not run the code twice (only once)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ SafeRunner

Returns a new instance of SafeRunner.

Parameters:

  • block (Proc)

    code we want to safe-guard



16
17
18
19
20
21
22
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 16

def initialize(&block)
  @code = block
  @executed = false
  @success = false
  @error = nil
  @result = nil
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



13
14
15
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 13

def error
  @error
end

#resultObject (readonly)

Returns the value of attribute result.



13
14
15
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 13

def result
  @result
end

Instance Method Details

#callObject

Runs the execution and returns block result



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 39

def call
  return @result if executed?

  @executed = true
  @result = @code.call
  @success = true
  @result
rescue StandardError => e
  @error = e
  @success = false
end

#executed?Boolean

Returns was the code executed already or not yet.

Returns:

  • (Boolean)

    was the code executed already or not yet



52
53
54
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 52

def executed?
  @executed
end

#failure?Boolean

Returns was the code execution failed or not.

Returns:

  • (Boolean)

    was the code execution failed or not



34
35
36
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 34

def failure?
  !success?
end

#success?Boolean

Returns was the code execution successful or not.

Returns:

  • (Boolean)

    was the code execution successful or not



25
26
27
28
29
30
31
# File 'lib/karafka/web/ui/lib/safe_runner.rb', line 25

def success?
  return @success if executed?

  call

  @success
end