Class: Trailblazer::Option

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

Constant Summary collapse

VERSION =
'0.1.2'

Class Method Summary collapse

Class Method Details

.build(value) ⇒ 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).



43
44
45
46
47
48
49
50
51
# File 'lib/trailblazer/option.rb', line 43

def self.build(value)
  evaluate = case value
             when Symbol then  method(:evaluate_method)
             when Proc   then  method(:evaluate_proc)
             else              method(:evaluate_callable)
             end

  ->(*args, **options, &block) { evaluate.(value, *args, **options, &block) }
end

.call!(value, *args, signal: :call, keyword_arguments: nil, &block) ⇒ Object

Don’t pass empty ‘keyword_arguments` because Ruby <= 2.6 passes an empty hash for `**{}`



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

def self.call!(value, *args, signal: :call, keyword_arguments: {}, **, &block)
  # NOTE: {**keyword_arguments} gets removed automatically if it's an empty hash.
  value.public_send(signal, *args, **keyword_arguments, &block)
end

.evaluate_callable(value, *args, **options, &block) ⇒ Object

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



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

def self.evaluate_callable(value, *args, **options, &block)
  call!(value, *args, **options, &block)
end

.evaluate_method(value, *args, exec_context: raise("No :exec_context given."), **options, &block) ⇒ Object

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



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

def self.evaluate_method(value, *args, exec_context: raise("No :exec_context given."), **options, &block)
  call!(exec_context.method(value), *args, **options, &block)
end

.evaluate_proc(value, *args, signal: :instance_exec, exec_context: raise("No :exec_context given."), **options) ⇒ Object

Pass given ‘value` as a block and evaluate it within `exec_context` binding.



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

def self.evaluate_proc(value, *args, signal: :instance_exec, exec_context: raise("No :exec_context given."), **options)
  call!(exec_context, *args, signal: signal, **options, &value)
end