Class: PusherFake::Connection

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

Overview

A client connection.

Constant Summary collapse

CLIENT_EVENT_PREFIX =

Prefix for client events.

"client-"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Connection

Create a new PusherFake::Connection object.

Parameters:

  • socket (EventMachine::WebSocket::Connection)

    Connection object.



15
16
17
# File 'lib/pusher-fake/connection.rb', line 15

def initialize(socket)
  @socket = socket
end

Instance Attribute Details

#socketEventMachine::WebSocket::Connection (readonly)

Returns Socket for the connection.

Returns:

  • (EventMachine::WebSocket::Connection)

    Socket for the connection.



10
11
12
# File 'lib/pusher-fake/connection.rb', line 10

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.



34
35
36
37
38
39
40
41
# File 'lib/pusher-fake/connection.rb', line 34

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.



44
45
46
47
# File 'lib/pusher-fake/connection.rb', line 44

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.



22
23
24
25
26
27
# File 'lib/pusher-fake/connection.rb', line 22

def id
  parts = socket.object_id.to_s.chars
  parts = parts.each_slice((parts.length / 2.0).ceil).to_a

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

#process(data) ⇒ Object

Process an event.

Parameters:

  • data (String)

    The event data as JSON.



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/pusher-fake/connection.rb', line 52

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

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

  if event.start_with?(CLIENT_EVENT_PREFIX)
    process_trigger(event, message)
  else
    process_event(event, message)
  end
end