Method: DataMapper::Hook::ClassMethods#register_hook

Defined in:
lib/dm-core/support/hook.rb

#register_hook(target_method, scope) ⇒ Object

Registers a method as hookable. Registering hooks involves the following process

  • Create a blank entry in the HOOK Hash for the method.

  • Define the methods that execute the before and after hook stack. These methods will be no-ops at first, but everytime a new hook is defined, the methods will be redefined to incorporate the new hook.

  • Redefine the method that is to be hookable so that the hook stacks are invoked approprietly.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/dm-core/support/hook.rb', line 165

def register_hook(target_method, scope)
  if scope == :instance && !method_defined?(target_method)
    raise ArgumentError, "#{target_method} instance method does not exist"
  elsif scope == :class && !respond_to?(target_method)
    raise ArgumentError, "#{target_method} class method does not exist"
  end

  hooks = hooks_with_scope(scope)

  if hooks[target_method].nil?
    hooks[target_method] = {
      # We need to keep track of which class in the Inheritance chain the
      # method was declared hookable in. Every time a child declares a new
      # hook for the method, the hook stack invocations need to be redefined
      # in the original Class. See #define_hook_stack_execution_methods
      :before => [], :after => [], :in => self
    }

    define_hook_stack_execution_methods(target_method, scope)
    define_advised_method(target_method, scope)
  end
end