Module: Shanty::Mixins::Callbacks

Included in:
Project
Defined in:
lib/shanty/mixins/callbacks.rb

Overview

A mixin to implement publish/subscribe style callbacks in the class that includes this.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(cls) ⇒ Object

The self.included idiom. This is described in great detail in a fantastic blog post here:

www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

Basically, this idiom allows us to add both instance and class methods to the class that is mixing this module into itself without forcing them to call extend and include for this mixin. You’ll see this idiom everywhere in the Ruby/Rails world, so we use it too.



15
16
17
# File 'lib/shanty/mixins/callbacks.rb', line 15

def self.included(cls)
  cls.extend(ClassMethods)
end

Instance Method Details

#callbacksObject



32
33
34
# File 'lib/shanty/mixins/callbacks.rb', line 32

def callbacks
  @callbacks ||= Hash.new { |h, k| h[k] = [] }
end

#publish(name, *args) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/shanty/mixins/callbacks.rb', line 42

def publish(name, *args)
  class_callback_methods = self.class.class_callbacks[name]
  callback_methods = callbacks[name]

  (class_callback_methods + callback_methods).each { |method| return false unless send(method, *args) }
  true
end

#subscribe(*names, sym) ⇒ Object



36
37
38
39
40
# File 'lib/shanty/mixins/callbacks.rb', line 36

def subscribe(*names, sym)
  names.each do |name|
    callbacks[name] << sym
  end
end