Class: Sinatra::PubSub::Stream
- Inherits:
-
Object
- Object
- Sinatra::PubSub::Stream
- Defined in:
- lib/sinatra/pubsub/stream.rb
Instance Attribute Summary collapse
-
#id ⇒ Object
readonly
Returns the value of attribute id.
-
#out ⇒ Object
readonly
Returns the value of attribute out.
Class Method Summary collapse
- .disable! ⇒ Object
- .enabled? ⇒ Boolean
- .publish(channel, message, options = {}) ⇒ Object
- .publish_all(message, options = {}) ⇒ Object
- .streams ⇒ Object
Instance Method Summary collapse
- #close! ⇒ Object
-
#initialize(out) ⇒ Stream
constructor
A new instance of Stream.
- #publish(event, message) ⇒ Object
- #subscribe(channel) ⇒ Object
Constructor Details
#initialize(out) ⇒ Stream
Returns a new instance of Stream.
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/sinatra/pubsub/stream.rb', line 36 def initialize(out) @id = SecureRandom.uuid @out = out subscribe :all @timer = EventMachine::PeriodicTimer.new( 20, method(:keepalive) ) setup end |
Instance Attribute Details
#id ⇒ Object (readonly)
Returns the value of attribute id.
34 35 36 |
# File 'lib/sinatra/pubsub/stream.rb', line 34 def id @id end |
#out ⇒ Object (readonly)
Returns the value of attribute out.
34 35 36 |
# File 'lib/sinatra/pubsub/stream.rb', line 34 def out @out end |
Class Method Details
.disable! ⇒ Object
15 16 17 18 |
# File 'lib/sinatra/pubsub/stream.rb', line 15 def self.disable! @enabled = false streams.values.flatten.each(&:close!) end |
.enabled? ⇒ Boolean
8 9 10 11 12 13 |
# File 'lib/sinatra/pubsub/stream.rb', line 8 def self.enabled? unless defined? @enabled @enabled = true end @enabled end |
.publish(channel, message, options = {}) ⇒ Object
20 21 22 23 24 25 26 27 28 |
# File 'lib/sinatra/pubsub/stream.rb', line 20 def self.publish(channel, , = {}) streams = self.streams[channel.to_s] if except_id = [:except] streams = streams.reject {|s| s.id == except_id } end streams.each {|c| c.publish(:message, ) } end |
.publish_all(message, options = {}) ⇒ Object
30 31 32 |
# File 'lib/sinatra/pubsub/stream.rb', line 30 def self.publish_all(, = {}) publish(:all, , ) end |
.streams ⇒ Object
4 5 6 |
# File 'lib/sinatra/pubsub/stream.rb', line 4 def self.streams @streams ||= Hash.new { |hash, key| hash[key] = [] } end |
Instance Method Details
#close! ⇒ Object
53 54 55 56 57 58 59 |
# File 'lib/sinatra/pubsub/stream.rb', line 53 def close! @timer.cancel self.class.streams.each do |channel, streams| streams.delete(self) end end |
#publish(event, message) ⇒ Object
61 62 63 64 |
# File 'lib/sinatra/pubsub/stream.rb', line 61 def publish(event, ) self << "event: #{event}\n" self << "data: #{}\n\n" end |
#subscribe(channel) ⇒ Object
49 50 51 |
# File 'lib/sinatra/pubsub/stream.rb', line 49 def subscribe(channel) self.class.streams[channel.to_s] << self end |