Class: PusherFake::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/pusher-fake/connection.rb

Constant Summary collapse

CLIENT_EVENT_MATCHER =

Name matcher for client events.

/\Aclient-(.+)\Z/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Connection

Create a new PusherFake::Connection object.

Parameters:

  • socket (EventMachine::WebSocket::Connection)

    The socket object for the connection.



12
13
14
# File 'lib/pusher-fake/connection.rb', line 12

def initialize(socket)
  @socket = socket
end

Instance Attribute Details

#socketEventMachine::WebSocket::Connection (readonly)

Returns The socket object for this connection.

Returns:

  • (EventMachine::WebSocket::Connection)

    The socket object for this connection.



7
8
9
# File 'lib/pusher-fake/connection.rb', line 7

def socket
  @socket
end

Instance Method Details

#emit(event, data = {}, channel = nil) ⇒ Object

Emit an event to the connection.

Parameters:

  • event (String)

    The event name.

  • data (Hash) (defaults to: {})

    The event data.

  • channel (String) (defaults to: nil)

    The channel name.



31
32
33
34
35
36
37
38
# File 'lib/pusher-fake/connection.rb', line 31

def emit(event, data = {}, channel = nil)
  message = { event: event, data: MultiJson.dump(data) }
  message[:channel] = channel if channel

  PusherFake.log("SEND #{id}: #{message}")

  socket.send(MultiJson.dump(message))
end

#establishObject

Notify the Pusher client that a connection has been established.



41
42
43
# File 'lib/pusher-fake/connection.rb', line 41

def establish
  emit("pusher:connection_established", socket_id: id, activity_timeout: 120)
end

#idInteger

The ID of the connection.

Returns:

  • (Integer)

    The object ID of the socket.



19
20
21
22
23
24
# File 'lib/pusher-fake/connection.rb', line 19

def id
  parts = socket.object_id.to_s.split("")
  parts = parts.each_slice(parts.length / 2).to_a

  [parts.first.join(""), parts.last.join("")].join(".")
end

#process(data) ⇒ Object

Process an event.

Parameters:

  • data (String)

    The event data as JSON.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/pusher-fake/connection.rb', line 48

def process(data)
  message = MultiJson.load(data, symbolize_keys: true)

  PusherFake.log("RECV #{id}: #{message}")

  data    = message[:data]
  event   = message[:event]
  name    = message[:channel] || data[:channel]
  channel = Channel.factory(name) if name

  case event
  when "pusher:subscribe"
    channel.add(self, data)
  when "pusher:unsubscribe"
    channel.remove(self)
  when "pusher:ping"
    emit("pusher:pong")
  when CLIENT_EVENT_MATCHER
    if channel.is_a?(Channel::Private) && channel.includes?(self)
      channel.emit(event, data, socket_id: id)

      trigger(channel, id, event, data)
    end
  end
end