Module: CallMeRuby
- Defined in:
- lib/call_me_ruby.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
-
.included(cls) ⇒ Object
The self.included idiom.
Instance Method Summary collapse
- #callbacks ⇒ Object
- #publish(name, *args) ⇒ Object
- #subscribe(name, *methods, &block) ⇒ Object
- #subscribed?(name) ⇒ Boolean
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/call_me_ruby.rb', line 15 def self.included(cls) cls.extend(ClassMethods) end |
Instance Method Details
#callbacks ⇒ Object
31 32 33 |
# File 'lib/call_me_ruby.rb', line 31 def callbacks @callbacks ||= Hash.new { |h, k| h[k] = [] } end |
#publish(name, *args) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/call_me_ruby.rb', line 40 def publish(name, *args) class_callback_methods = self.class.class_callbacks[name] callback_methods = callbacks[name] (class_callback_methods + callback_methods).each do |callback| result = (callback.respond_to?(:call) ? callback.call(*args) : send(callback, *args)) # Exit early if the block explicitly returns `false`. return false if result == false end true end |
#subscribe(name, *methods, &block) ⇒ Object
35 36 37 38 |
# File 'lib/call_me_ruby.rb', line 35 def subscribe(name, *methods, &block) methods.each { |method| callbacks[name] << method } callbacks[name] << block if block_given? end |
#subscribed?(name) ⇒ Boolean
53 54 55 |
# File 'lib/call_me_ruby.rb', line 53 def subscribed?(name) self.class.class_callbacks.include?(name) || callbacks.include?(name) end |