Module: Ducktape::Hookable

Included in:
Array, BindableAttribute, Hash, String
Defined in:
lib/ducktape/hookable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(_) ⇒ Object



24
25
26
# File 'lib/ducktape/hookable.rb', line 24

def self.extended(_)
  raise 'Cannot extend, only include.'
end

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ducktape/hookable.rb', line 3

def self.included(base)
  base.extend ClassMethods

  return if base.is_a?(Class)

  # Module

  # just create a proxy for #included
  include_method = if base.respond_to?(:included)
    base_included_method = base.method(:included)
    ->(c) do
      base_included_method.(c)
      c.send :include, ::Ducktape::Hookable
    end
  else
    ->(c) { c.send :include, ::Ducktape::Hookable }
  end

  base.define_singleton_method(:included, include_method)
end

Instance Method Details

#add_hook(event, hook = nil, &block) ⇒ Object

Registers a block, a named method, or any object that responds to call to be triggered when the event occurs.

Raises:

  • (ArgumentError)


104
105
106
107
108
109
110
# File 'lib/ducktape/hookable.rb', line 104

def add_hook(event, hook = nil, &block)
  hook = block if block #block has precedence
  raise ArgumentError, 'no hook was passed' unless hook
  hook = hook.to_s unless hook.respond_to?(:call)
  hooks[event.to_s].unshift(hook)
  hook
end

#clear_hooks(event = nil) ⇒ Object

Removes all hooks from the specified event. If an event wasn’t passed, removes all hooks from all events.



121
122
123
124
125
126
127
128
129
# File 'lib/ducktape/hookable.rb', line 121

def clear_hooks(event = nil)
  if event
    hooks.delete(event.to_s) if hooks.has_key?(event.to_s)
    return
  end

  hooks.clear
  nil
end

#on_changed(hook = nil, &block) ⇒ Object

Generic event. It’s called for all triggered events.



132
133
134
# File 'lib/ducktape/hookable.rb', line 132

def on_changed(hook = nil, &block)
  add_hook __method__, hook, &block
end

#remove_hook(event, hook) ⇒ Object

Removes the specified hook. Returns nil if the hook wasn’t found.



113
114
115
116
117
# File 'lib/ducktape/hookable.rb', line 113

def remove_hook(event, hook)
  return unless hooks.has_key?(event.to_s)
  hook = hook.to_s unless hook.respond_to?(:call)
  hooks[event.to_s].delete(hook)
end