Module: Perennial::Hookable::ClassMethods

Defined in:
lib/perennial/hookable.rb

Instance Method Summary collapse

Instance Method Details

#append_hook(type, &blk) ⇒ Object

Append a hook for a given type of hook in order to be called later on via invoke_hooks!



28
29
30
# File 'lib/perennial/hookable.rb', line 28

def append_hook(type, &blk)
  self.hooks_for(type) << blk unless blk.blank?
end

#define_hook(*args) ⇒ Object

Defines a set of handy methods to make it easy to define simplistic block based hooks on an arbitrary class.



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/perennial/hookable.rb', line 47

def define_hook(*args)
  klass = self.metaclass
  args.map { |a| a.to_sym }.each do |name|
    
    klass.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
      def #{name}(&blk)               # def before_run(&blk)
        append_hook(:#{name}, &blk)   #   append_hook(:before_run, &blk)
      end                             # end
    RUBY
    
  end
end

#hooks_for(type) ⇒ Object

Return all of the existing hooks or an empty for a given hook type.



34
35
36
# File 'lib/perennial/hookable.rb', line 34

def hooks_for(type)
  self.hooks[type.to_sym]
end

#invoke_hooks!(type) ⇒ Object

Invoke (call) all of the hooks for a given type.



40
41
42
# File 'lib/perennial/hookable.rb', line 40

def invoke_hooks!(type)
  hooks_for(type).each { |hook| hook.call }
end