Class: Sinatra::PubSub::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatra/pubsub/stream.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#idObject (readonly)

Returns the value of attribute id.



34
35
36
# File 'lib/sinatra/pubsub/stream.rb', line 34

def id
  @id
end

#outObject (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

Returns:

  • (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, message, options = {})
  streams = self.streams[channel.to_s]

  if except_id = options[:except]
    streams = streams.reject {|s| s.id == except_id }
  end

  streams.each {|c| c.publish(:message, message) }
end

.publish_all(message, options = {}) ⇒ Object



30
31
32
# File 'lib/sinatra/pubsub/stream.rb', line 30

def self.publish_all(message, options = {})
  publish(:all, message, options)
end

.streamsObject



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, message)
  self << "event: #{event}\n"
  self << "data: #{message}\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