Class: Hooks::Hook

Inherits:
Array
  • Object
show all
Defined in:
lib/hooks/hook.rb

Defined Under Namespace

Classes: Results

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Hook

Returns a new instance of Hook.


5
6
7
8
# File 'lib/hooks/hook.rb', line 5

def initialize(options)
  super()
  @options = options
end

Instance Method Details

#<<(callback) ⇒ Object


47
48
49
# File 'lib/hooks/hook.rb', line 47

def <<(callback)
  super Uber::Options::Value.new(callback, :dynamic => true) # allows string and symbol method names.
end

#run(scope, *args) ⇒ Object

The chain contains the return values of the executed callbacks.

Example:

class Person
  define_hook :before_eating

  before_eating :wash_hands
  before_eating :locate_food
  before_eating :sit_down

  def wash_hands; :washed_hands; end
  def locate_food; :located_food; false; end
  def sit_down; :sat_down; end
end

result = person.run_hook(:before_eating)
result.chain #=> [:washed_hands, false, :sat_down]

If :halts_on_falsey is enabled:

class Person
  define_hook :before_eating, :halts_on_falsey => true
  # ...
end

result = person.run_hook(:before_eating)
result.chain #=> [:washed_hands]

38
39
40
41
42
43
44
45
# File 'lib/hooks/hook.rb', line 38

def run(scope, *args)
  inject(Results.new) do |results, callback|
    executed = execute_callback(scope, callback, *args)

    return results.halted! unless continue_execution?(executed)
    results << executed
  end
end