Class: ServerSentEvents::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/server_sent_events/event.rb

Overview

Class that represents server event.

This class can be used to construct new events on the server and then serialize them for the transfer or is returned as a result of Parser action on the client.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEvent

Returns a new instance of Event.



12
13
14
# File 'lib/server_sent_events/event.rb', line 12

def initialize
  @data = ""
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



10
11
12
# File 'lib/server_sent_events/event.rb', line 10

def data
  @data
end

#eventObject (readonly)

Returns the value of attribute event.



10
11
12
# File 'lib/server_sent_events/event.rb', line 10

def event
  @event
end

#idObject (readonly)

Returns the value of attribute id.



10
11
12
# File 'lib/server_sent_events/event.rb', line 10

def id
  @id
end

Instance Method Details

#==(other) ⇒ Object



48
49
50
# File 'lib/server_sent_events/event.rb', line 48

def ==(other)
  other.id == id && other.event == event && other.data == data
end

#set(key, value) ⇒ Object

Set event key-value pair.

Note that the only valid keys are id, event and data, last one being a bit special. Calling set("data", "some data") will apend this the string some data to existing data using newline as a separator.

Parameters:

  • key (String)

    key to use

  • value (String)

    data to set/append



25
26
27
28
29
30
31
# File 'lib/server_sent_events/event.rb', line 25

def set(key, value)
  case key
  when "id"    then @id = value
  when "event" then @event = value
  when "data"  then append_data(value)
  end
end

#to_sObject

Serialize event into form for transmission.

Output of this method call can be written directly into the socket.



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/server_sent_events/event.rb', line 36

def to_s
  repr = ""
  repr += "id: #{id}\n" if id
  repr += "event: #{event}\n" if event
  if data.empty?
    repr += "data: \n"
  else
    data.split("\n").each { |l| repr += "data: #{l}\n" }
  end
  repr += "\n"
end