Module: Spinach::Hookable::InstanceMethods

Defined in:
lib/spinach/hookable.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#hooksHash

Returns hash in which the key is the hook name and the value an array of any defined callbacks, or nil.

Returns:

  • (Hash)

    hash in which the key is the hook name and the value an array of any defined callbacks, or nil.



55
56
57
# File 'lib/spinach/hookable.rb', line 55

def hooks
  @hooks ||= {}
end

Instance Method Details

#add_hook(name, &block) ⇒ Object

Adds a hook to the queue

Parameters:

  • name (String)

    the hook’s identifier

  • block (Proc)

    an action to perform once that hook is executed



119
120
121
122
# File 'lib/spinach/hookable.rb', line 119

def add_hook(name, &block)
  hooks[name.to_sym] ||= []
  hooks[name.to_sym] << block
end

#hooks_for(name) ⇒ Array

Returns array of hooks for that particular identifier.

Parameters:

  • name (String)

    the hook’s identifier

Returns:

  • (Array)

    array of hooks for that particular identifier



108
109
110
# File 'lib/spinach/hookable.rb', line 108

def hooks_for(name)
  hooks[name.to_sym] || []
end

#resetObject

Resets all this class’ hooks to a pristine state



60
61
62
# File 'lib/spinach/hookable.rb', line 60

def reset
  self.hooks = {}
end

#run_around_hook(name, *args, &block) ⇒ Object

Runs around hooks in a way that ensure the scenario block is executed only once

Parameters:

  • name (String)

    the around hook’s name

  • []

    args the list of arguments to pass to other around filters

  • block (Proc)

    the block containing the scenario action to be executed

Raises:

  • (ArgumentError)


75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/spinach/hookable.rb', line 75

def run_around_hook(name, *args, &block)
  raise ArgumentError.new("block is mandatory") unless block
  if callbacks = hooks[name.to_sym]
    callbacks.reverse.inject(block) do |blk, callback|
      proc do
        callback.call *args do
          blk.call
        end
      end
    end.call
  else
    yield
  end
end

#run_hook(name, *args, &block) ⇒ Object

Runs a particular hook given a set of arguments

Parameters:

  • name (String)

    the hook’s name



95
96
97
98
99
100
101
# File 'lib/spinach/hookable.rb', line 95

def run_hook(name, *args, &block)
  if callbacks = hooks[name.to_sym]
    callbacks.each{ |c| c.call(*args, &block) }
  else
    yield if block
  end
end