Class: Brainguy::SubscriptionScope
- Defined in:
- lib/brainguy/subscription_scope.rb
Overview
A scope for subscriptions with a limited lifetime.
Sometimes it's useful to have a set of subscriptions with a limited
lifetime. For instance, a set of observers which are only valid over the
course of a single method call. This class wraps an existing
Emitter, and exposes the same API. But when a client sends the
#close
message, all listeners subscribed through this object will be
immediately unsubscribed.
Constant Summary
Constants inherited from Emitter
Class Method Summary collapse
-
.open(subscription_set) {|SubscriptionScope| ... } ⇒ Object
Create a new scope and yield it to the block.
Instance Method Summary collapse
-
#attach ⇒ Subscription
Attach a new object to listen for events.
-
#close ⇒ void
Detach every listener that was attached via this scope.
-
#initialize(subscription_set) ⇒ SubscriptionScope
constructor
A new instance of SubscriptionScope.
-
#on ⇒ Subscription
Attach blocks of code to handle specific named events.
Methods inherited from Emitter
#detach, #emit, new_from_existing, #subscriptions, #with_subscription_scope
Constructor Details
#initialize(subscription_set) ⇒ SubscriptionScope
Returns a new instance of SubscriptionScope.
28 29 30 31 |
# File 'lib/brainguy/subscription_scope.rb', line 28 def initialize(subscription_set) super(subscription_set) @subscriptions = [] end |
Class Method Details
.open(subscription_set) {|SubscriptionScope| ... } ⇒ Object
Create a new scope and yield it to the block. Closes the scope (unsubscribing any listeners attached using the scope) at the end of block execution
20 21 22 23 24 25 |
# File 'lib/brainguy/subscription_scope.rb', line 20 def self.open(subscription_set) scope = self.new(subscription_set) yield scope ensure scope.close end |
Instance Method Details
#attach ⇒ Subscription
Attach a new object to listen for events. A listener is expected to be
call-able, and it will receive the #call
message with an Event each
time one is emitted.
41 42 43 44 45 |
# File 'lib/brainguy/subscription_scope.rb', line 41 def attach(*) super.tap do |subscription| @subscriptions << subscription end end |
#close ⇒ void
This method returns an undefined value.
Detach every listener that was attached via this scope.
49 50 51 52 |
# File 'lib/brainguy/subscription_scope.rb', line 49 def close @subscriptions.each(&:cancel) @subscriptions.clear end |
#on(name, &block) ⇒ Subscription #on(handlers) ⇒ Subscription
Attach blocks of code to handle specific named events.
34 35 36 37 38 |
# File 'lib/brainguy/subscription_scope.rb', line 34 def on(*) super.tap do |subscription| @subscriptions << subscription end end |