Class: RMessage::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/rmessage/message.rb

Overview

A Message encapsulates a JSON payload that is sent to or received from Redis.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Message

Constructs a new Message

  • type [Symbol, String] the Message label

  • signature [Integer, String] the Message signature

  • payload [Hash, String] the Message data

Parameters:

  • opts (Hash, String) (defaults to: {})

    message options



22
23
24
25
26
# File 'lib/rmessage/message.rb', line 22

def initialize(opts = {})
  @type = opts[:type] || opts['type'] || :UNTITLED
  @signature = opts[:signature] || opts['signature']
  read(opts)
end

Instance Attribute Details

#payloadHash (readonly)

Returns the payload.

Returns:

  • (Hash)

    the payload.



15
16
17
# File 'lib/rmessage/message.rb', line 15

def payload
  @payload
end

#signatureInteger, String (readonly)

Returns the signature.

Returns:

  • (Integer, String)

    the signature.



11
12
13
# File 'lib/rmessage/message.rb', line 11

def signature
  @signature
end

#typeSymbol, String (readonly)

Returns the label.

Returns:

  • (Symbol, String)

    the label.



7
8
9
# File 'lib/rmessage/message.rb', line 7

def type
  @type
end

Instance Method Details

#build(data = @payload) ⇒ Object

Build a JSON string using data in this message

Parameters:

  • data (Hash, String) (defaults to: @payload)

    the payload.



49
50
51
# File 'lib/rmessage/message.rb', line 49

def build(data = @payload)
  Oj.dump({ 'type' => @type, 'signature' => @signature, 'payload' => data })
end

#read(data = @payload) ⇒ RMessage::Message

Read and parse data. Defaults to the Message#payload.

Parameters:

  • data (Hash, String) (defaults to: @payload)

    the data.

Returns:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rmessage/message.rb', line 31

def read(data = @payload)
  case data
  when Hash
    @type = data[:type]
    @signature ||= data[:signature]
    @payload = data[:payload] || data
  when String
    parsed = Oj.load(data)
    @type = parsed['type']
    @signature ||= parsed['signature']
    @payload = parsed['payload'] || parsed
  else raise TypeError, 'Invalid type for Message#payload'
  end
  self
end