Class: MARS::Gate

Inherits:
Runnable show all
Defined in:
lib/mars/gate.rb

Class Attribute Summary collapse

Attributes inherited from Runnable

#formatter, #name, #state

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Runnable

formatter, step_name

Methods included from Hooks

included, #run_after_hooks, #run_before_hooks

Constructor Details

#initialize(name = "Gate", check: nil, fallbacks: nil, **kwargs) ⇒ Gate

Returns a new instance of Gate.



21
22
23
24
25
26
# File 'lib/mars/gate.rb', line 21

def initialize(name = "Gate", check: nil, fallbacks: nil, **kwargs)
  super(name: name, **kwargs)

  @check = check || self.class.check_block
  @fallbacks = fallbacks || self.class.fallbacks_map
end

Class Attribute Details

.check_blockObject (readonly)

Returns the value of attribute check_block.



10
11
12
# File 'lib/mars/gate.rb', line 10

def check_block
  @check_block
end

Class Method Details

.check(&block) ⇒ Object



6
7
8
# File 'lib/mars/gate.rb', line 6

def check(&block)
  @check_block = block
end

.fallback(key, runnable) ⇒ Object



12
13
14
# File 'lib/mars/gate.rb', line 12

def fallback(key, runnable)
  fallbacks_map[key] = runnable
end

.fallbacks_mapObject



16
17
18
# File 'lib/mars/gate.rb', line 16

def fallbacks_map
  @fallbacks_map ||= {}
end

Instance Method Details

#run(context) ⇒ Object

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mars/gate.rb', line 28

def run(context)
  context = ensure_context(context)
  result = check.call(context)

  return context if result.nil? || result == :default

  branch = fallbacks[result]
  raise ArgumentError, "No fallback registered for #{result.inspect}" unless branch

  resolve_branch(branch).run(context)
end