Class: Brainguy::OpenObserver
- Inherits:
-
Object
- Object
- Brainguy::OpenObserver
- Defined in:
- lib/brainguy/open_observer.rb
Overview
A quick and dirty way to set up a reusable listener object. Like an OpenObject, only for event listening!
Instance Method Summary collapse
-
#call(event) ⇒ Object
Dispatch the event to the appropriate handler, if one has been set.
-
#initialize(handlers = {}) {|self| ... } ⇒ OpenObserver
constructor
end.
-
#method_missing(method_name, *_args, &block) ⇒ Object
Enable setting up event handlers dynamically using
on_*
message sends. -
#respond_to_missing?(method_name, _include_private) ⇒ Boolean
true if the method starts with
on_
.
Constructor Details
#initialize(handlers = {}) {|self| ... } ⇒ OpenObserver
end
27 28 29 30 |
# File 'lib/brainguy/open_observer.rb', line 27 def initialize(handlers = {}) @handlers = handlers yield self if block_given? end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *_args, &block) ⇒ Object
Enable setting up event handlers dynamically using on_*
message sends.
50 51 52 53 54 55 56 57 |
# File 'lib/brainguy/open_observer.rb', line 50 def method_missing(method_name, *_args, &block) if method_name.to_s =~ /\Aon_(.+)/ @handlers[$1.to_sym] = block self else super end end |
Instance Method Details
#call(event) ⇒ Object
Dispatch the event to the appropriate handler, if one has been set. Events without handlers are ignored.
35 36 37 38 39 |
# File 'lib/brainguy/open_observer.rb', line 35 def call(event) if (handler = @handlers[event.name]) handler.call(event) end end |
#respond_to_missing?(method_name, _include_private) ⇒ Boolean
true if the method starts with on_
61 62 63 |
# File 'lib/brainguy/open_observer.rb', line 61 def respond_to_missing?(method_name, _include_private) method_name.to_s =~ /\Aon_./ end |