Class: Lotus::Utils::Callbacks::Chain

Inherits:
Array
  • Object
show all
Defined in:
lib/lotus/utils/callbacks.rb

Overview

Series of callbacks to be executed

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#add(*callbacks, &blk) ⇒ void

This method returns an undefined value.

Adds the given callbacks to the chain

Examples:

require 'lotus/utils/callbacks'

chain = Lotus::Utils::Callbacks::Chain.new

# Add a Proc to be used as a callback, it will be wrapped by `Callback`
# The optional argument(s) correspond to the one passed when invoked the chain with `run`.
chain.add { Authenticator.authenticate! }
chain.add {|params| ArticleRepository.find(params[:id]) }

# Add a Symbol as a reference to a method name that will be used as a callback.
# It will wrapped by `MethodCallback`
# If the #notificate method accepts some argument(s) they should be passed when `run` is invoked.
chain.add :notificate

Parameters:

  • callbacks (Array)

    one or multiple callbacks to add

  • blk (Proc)

    an optional block to be added

See Also:

Since:

  • 0.1.0



40
41
42
43
44
45
46
47
# File 'lib/lotus/utils/callbacks.rb', line 40

def add(*callbacks, &blk)
  callbacks.push blk if block_given?
  callbacks.each do |c|
    push Factory.fabricate(c)
  end

  uniq!
end

#run(context, *args) ⇒ Object

Runs all the callbacks in the chain. The only two ways to stop the execution are: ‘raise` or `throw`.

Examples:

require 'lotus/utils/callbacks'

class Action
  private
  def authenticate!
  end

  def set_article(params)
  end
end

action = Action.new
params = Hash[id: 23]

chain = Lotus::Utils::Callbacks::Chain.new
chain.add :authenticate!, :set_article

chain.run(action, params)

# `params` will only be passed as #set_article argument, because it has an arity greater than zero

chain = Lotus::Utils::Callbacks::Chain.new

chain.add do
  # some authentication logic
end

chain.add do |params|
  # some other logic that requires `params`
end

chain.run(action, params)

Those callbacks will be invoked within the context of `action`.

Parameters:

  • context (Object)

    the context where we want the chain to be invoked.

  • args (Array)

    the arguments that we want to pass to each single callback.

Since:

  • 0.1.0



94
95
96
97
98
# File 'lib/lotus/utils/callbacks.rb', line 94

def run(context, *args)
  each do |callback|
    callback.call(context, *args)
  end
end