Class: Angelo::Stash

Inherits:
Object
  • Object
show all
Includes:
Celluloid::Logger
Defined in:
lib/angelo/stash.rb

Overview

utility class for stashing connected websockets in arbitrary contexts

Constant Summary collapse

@@peeraddrs =

hold the peeraddr info for use after the socket is closed (logging)

{}
@@stashes =

the underlying arrays of websockets, by context

{}

Instance Method Summary collapse

Constructor Details

#initialize(server, context = :default) ⇒ Stash

create a new instance with a context, creating the array if needed



18
19
20
21
22
# File 'lib/angelo/stash.rb', line 18

def initialize server, context = :default
  raise ArgumentError.new "symbol required" unless Symbol === context
  @context, @server = context, server
  @@stashes[@context] ||= []
end

Instance Method Details

#<<(ws) ⇒ Object

add a websocket to this context’s stash, save peeraddr info, start server handle_websocket task to read from the socket and fire events as needed



28
29
30
31
32
# File 'lib/angelo/stash.rb', line 28

def << ws
  @@peeraddrs[ws] = ws.peeraddr
  @server.async.handle_websocket ws
  @@stashes[@context] << ws
end

#[](context) ⇒ Object

utility method to create a new instance with a different context



65
66
67
# File 'lib/angelo/stash.rb', line 65

def [] context
  self.class.new @server, context
end

#all_eachObject

iterate on every connected websocket in all contexts, mostly used for ping_websockets task



72
73
74
75
76
77
78
79
80
# File 'lib/angelo/stash.rb', line 72

def all_each
  @@stashes.values.flatten.each do |ws|
    begin
      yield ws
    rescue IOError
      remove_socket ws
    end
  end
end

#each(&block) ⇒ Object

iterate on each connected websocket in this context, handling errors as needed



43
44
45
46
47
48
49
50
51
# File 'lib/angelo/stash.rb', line 43

def each &block
  stash.each do |ws|
    begin
      yield ws
    rescue Reel::SocketError
      remove_socket ws
    end
  end
end

#lengthObject

return the number of websockets in this context (some are potentially disconnected)



97
98
99
# File 'lib/angelo/stash.rb', line 97

def length
  stash.length
end

#peeraddr(ws) ⇒ Object

access the peeraddr info for a given websocket



90
91
92
# File 'lib/angelo/stash.rb', line 90

def peeraddr ws
  @@peeraddrs[ws]
end

#reject!(&block) ⇒ Object

pass the given block to the underlying stashed array’s reject! method



84
85
86
# File 'lib/angelo/stash.rb', line 84

def reject! &block
  stash.reject! &block
end

#remove_socket(ws) ⇒ Object

remove a websocket from the stash, warn user, drop peeraddr info



55
56
57
58
59
60
61
# File 'lib/angelo/stash.rb', line 55

def remove_socket ws
  if stash.include? ws
    warn "removing socket from context ':#{@context}' (#{@@peeraddrs[ws][2]})"
    stash.delete ws
    @@peeraddrs.delete ws
  end
end

#stashObject

access the underlying array of this context



36
37
38
# File 'lib/angelo/stash.rb', line 36

def stash
  @@stashes[@context]
end