module Shanty::Mixins::Callbacks

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

Public Class Methods

included(cls) click to toggle source

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.

# File lib/shanty/mixins/callbacks.rb, line 15
def self.included(cls)
  cls.extend(ClassMethods)
end

Public Instance Methods

callbacks() click to toggle source
# File lib/shanty/mixins/callbacks.rb, line 32
def callbacks
  @callbacks ||= Hash.new { |h, k| h[k] = [] }
end
publish(name, *args) click to toggle source
# 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) click to toggle source
# File lib/shanty/mixins/callbacks.rb, line 36
def subscribe(*names, sym)
  names.each do |name|
    callbacks[name] << sym
  end
end