Class: KHL::Message

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

Constant Summary collapse

TYPES =
%i[
  event
  hello
  ping
  pong
  resume
  reconnect
  resume_ack
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type: nil, data: nil, sn: nil) ⇒ Message

Returns a new instance of Message.



33
34
35
36
37
# File 'lib/khl/message.rb', line 33

def initialize(type: nil, data: nil, sn: nil)
  @type = type
  @data = data
  @sn = sn
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



18
19
20
# File 'lib/khl/message.rb', line 18

def data
  @data
end

#snObject

Returns the value of attribute sn.



18
19
20
# File 'lib/khl/message.rb', line 18

def sn
  @sn
end

#typeObject

Returns the value of attribute type.



18
19
20
# File 'lib/khl/message.rb', line 18

def type
  @type
end

Class Method Details

.parse(raw) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/khl/message.rb', line 20

def self.parse(raw)
  return unless raw

  data = raw.is_a?(String) ? JSON.parse(raw) : raw
  data = ActiveSupport::HashWithIndifferentAccess.new(data)

  Message.new(
    type: TYPES[data[:s]],
    data: data[:d],
    sn: data[:sn]
  )
end

Instance Method Details

#to_hObject



39
40
41
42
43
44
45
# File 'lib/khl/message.rb', line 39

def to_h
  ActiveSupport::HashWithIndifferentAccess.new(
    s: TYPES.index(type),
    d: data,
    sn: sn
  )
end

#to_jsonObject



47
48
49
# File 'lib/khl/message.rb', line 47

def to_json
  to_h.to_json
end