Class: WebRepl::Messenger

Inherits:
Object
  • Object
show all
Defined in:
lib/web-repl/messenger.rb

Overview

Handles sending and receiving messages to/from the socket

Instance Method Summary collapse

Constructor Details

#initialize(socket, options = {}) ⇒ Messenger

Returns a new instance of Messenger.

Parameters:

Options Hash (options):

  • :debug (Boolean)


9
10
11
12
# File 'lib/web-repl/messenger.rb', line 9

def initialize(socket, options = {})
  @socket = socket
  @debug = options[:debug]
end

Instance Method Details

#in(raw_message) {|hash| ... } ⇒ Hash

Handle an inputted message

Parameters:

  • raw_message (String)

    A raw inputted JSON message

Yields:

  • (hash)

Returns:

  • (Hash)


17
18
19
20
21
22
# File 'lib/web-repl/messenger.rb', line 17

def in(raw_message, &block)
  hash = JSON.parse(raw_message, :symbolize_names => true)
  hash[:timestamp] = Time.at(hash[:timestamp].to_i / 1000) if !hash[:timestamp].nil?
  yield(hash) if block_given?
  hash
end

#new_timestampFixnum

Generate a new timestamp in js format

Returns:

  • (Fixnum)


26
27
28
# File 'lib/web-repl/messenger.rb', line 26

def new_timestamp
  Time.now.to_i * 1000 # javascript time int format
end

#out(message) ⇒ String?

Send a message over the socket

Parameters:

  • message (Hash)

    A message to send

Returns:

  • (String, nil)

    If a message was sent, its JSON string; otherwise nil



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/web-repl/messenger.rb', line 33

def out(message)
  if !@socket.nil?
    message[:timestamp] ||= new_timestamp
    json = message.to_json
    @debug.puts "Sending message: #{json}" if @debug
    @socket.send(json)
    json
  else
    @debug.puts "Warning: No connection" if @debug
    nil
  end
end