Class: Bus
- Inherits:
-
Object
- Object
- Bus
- Defined in:
- lib/bus.rb,
lib/bus/version.rb
Defined Under Namespace
Classes: CallableListener, NoListenerRespondedError
Constant Summary collapse
- VERSION =
'0.0.3'
Instance Method Summary collapse
- #attach(listener) ⇒ Object
-
#initialize(listeners = []) ⇒ Bus
constructor
A new instance of Bus.
- #method_missing(method_name, *args) ⇒ Object
- #on(event_or_hash, &block) ⇒ Object (also: #when)
Constructor Details
#initialize(listeners = []) ⇒ Bus
Returns a new instance of Bus.
6 7 8 |
# File 'lib/bus.rb', line 6 def initialize(listeners = []) @listeners = listeners end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args) ⇒ Object
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/bus.rb', line 21 def method_missing(method_name, *args) responded = false @listeners.each do |listener| if listener.respond_to?(method_name) responded = true listener.public_send(method_name, *args) end end raise NoListenerRespondedError.new("No listener responded to message '#{method_name}'") unless responded end |
Instance Method Details
#attach(listener) ⇒ Object
10 11 12 |
# File 'lib/bus.rb', line 10 def attach(listener) self.class.new(@listeners + [listener]) end |
#on(event_or_hash, &block) ⇒ Object Also known as: when
14 15 16 17 |
# File 'lib/bus.rb', line 14 def on(event_or_hash, &block) listeners = block_given? ? [CallableListener.new(event_or_hash, block)] : build_listeners_from_hash(event_or_hash) self.class.new(@listeners + listeners) end |