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.



35
36
37
38
39
# File 'lib/khl/message.rb', line 35

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.



20
21
22
# File 'lib/khl/message.rb', line 20

def data
  @data
end

#snObject

Returns the value of attribute sn.



20
21
22
# File 'lib/khl/message.rb', line 20

def sn
  @sn
end

#typeObject

Returns the value of attribute type.



20
21
22
# File 'lib/khl/message.rb', line 20

def type
  @type
end

Class Method Details

.parse(raw) ⇒ Object



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

def self.parse(raw)
  return unless raw

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

  message = Message.new
  message.type = TYPES[data[:s]]
  message.data = data[:d]
  message.sn = data[:sn]
  message
end

Instance Method Details

#eventObject



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

def event
  return unless event?

  Event.new(@data)
end

#to_hObject



47
48
49
50
51
52
53
# File 'lib/khl/message.rb', line 47

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

#to_jsonObject



55
56
57
# File 'lib/khl/message.rb', line 55

def to_json
  to_h.to_json
end