Module: SendChain

Included in:
LruFile
Defined in:
lib/util/send_chain.rb

Overview

Supports one chain at a time

Instance Method Summary collapse

Instance Method Details

#new_chain(chain) ⇒ Object

Saves @chain structure containing :placeholders for arguments to be supplied later Call when a different chain with :placeholders is desired



14
15
16
17
18
# File 'lib/util/send_chain.rb', line 14

def new_chain(chain)
  abort "new_chain error: chain must be an array ('#{chain}' was an #{chain.class.name})" \
    unless chain.instance_of?(Array)
  @chain = chain
end

#send_chain(chain) ⇒ Object

See stackoverflow.com/a/79333706/553865 This method can be called directly if no methods in the chain require arguments Does not use any external state



8
9
10
# File 'lib/util/send_chain.rb', line 8

def send_chain(chain)
  Array(chain).inject(self) { |o, a| o.send(*a) }
end

#substitute_and_send_chain_with(values) ⇒ Object Also known as: evaluate_with

Call after new_chain, to evaluate @chain with values



21
22
23
# File 'lib/util/send_chain.rb', line 21

def substitute_and_send_chain_with(values)
  send_chain substitute_chain_with values
end

#substitute_chain_with(values) ⇒ Array

Call this method after calling new_chain to perform error checking and replace :placeholders with values.

Returns:

  • (Array)

    Modified chain



30
31
32
33
34
35
36
37
38
39
# File 'lib/util/send_chain.rb', line 30

def substitute_chain_with(values)
  values = [values] unless values.instance_of?(Array)

  placeholder_count = @chain.flatten.count { |x| x == :placeholder }
  if values.length != placeholder_count
    abort "with_values error: number of values (#{values.length}) does not match the number of placeholders (#{placeholder_count})"
  end

  eval_chain @chain, values
end