Class: Trailblazer::Option

Inherits:
Object
  • Object
show all
Defined in:
lib/trailblazer/option.rb

Direct Known Subclasses

KW

Defined Under Namespace

Classes: KW

Class Method Summary collapse

Class Method Details

.build(call_implementation, proc) ⇒ Proc

Generic builder for a callable “option”.

Parameters:

  • call_implementation (Class, Module)

    implements the process of calling the proc while passing arguments/options to it in a specific style (e.g. kw args, step interface).

Returns:

  • (Proc)

    when called, this proc will evaluate its option (at run-time).



12
13
14
15
16
17
18
# File 'lib/trailblazer/option.rb', line 12

def self.build(call_implementation, proc)
  if proc.is_a? Symbol
    ->(*args) { call_implementation.evaluate_method(proc, *args) }
  else
    ->(*args) { call_implementation.evaluate_callable(proc, *args) }
  end
end

.call!(proc, *args) ⇒ Object

A call implementation invoking ‘proc.(*args)` and plainly forwarding all arguments. Override this for your own step strategy (see KW#call!).



23
24
25
# File 'lib/trailblazer/option.rb', line 23

def self.call!(proc, *args)
  proc.(*args)
end

.evaluate_callable(proc, *args, **flow_options) ⇒ Object

Note that both #evaluate_callable and #evaluate_method drop most of the args. If you need those, override this class.



30
31
32
# File 'lib/trailblazer/option.rb', line 30

def self.evaluate_callable(proc, *args, **flow_options)
  call!(proc, *args)
end

.evaluate_method(proc, *args, exec_context: raise, **flow_options) ⇒ Object

Make the context’s instance method a “lambda” and reuse #call!.



36
37
38
# File 'lib/trailblazer/option.rb', line 36

def self.evaluate_method(proc, *args, exec_context:raise, **flow_options)
  call!(exec_context.method(proc), *args)
end

.KW(proc) ⇒ Object

Returns a Proc that, when called, invokes the ‘proc` argument with keyword arguments. This is known as “step (call) interface”.

This is commonly used by ‘Operation::step` to wrap the argument and make it callable in the circuit.

my_proc = ->(options, **kws) { options["i got called"] = true }
task    = Trailblazer::Option::KW(my_proc)
task.(options = {})
options["i got called"] #=> true

Alternatively, you can pass a symbol and an ‘:exec_context`.

my_proc = :some_method
task    = Trailblazer::Option::KW(my_proc)

class A
  def some_method(options, **kws)
    options["i got called"] = true
  end
end

task.(options = {}, exec_context: A.new)
options["i got called"] #=> true


64
65
66
# File 'lib/trailblazer/option.rb', line 64

def self.KW(proc)
  Option.build(KW, proc)
end