Method: ListSerializer.serialize

Defined in:
lib/rubyslim/list_serializer.rb

.serialize(list) ⇒ Object

Serialize a list according to the SliM protocol.

Lists are enclosed in square-brackets ‘[…]’. Inside the opening bracket is a six-digit number indicating the length of the list (number of items), then a colon ‘:’, then the serialization of each list item. For example:

[]         => "[000000:]"
["hello"]  => "[000001:000005:hello:]"
[1]        => "[000001:000001:1:]"

Strings are preceded by a six-digit sequence indicating their length:

""         => "000000:"
"hello"    => "000005:hello"
nil        => "000004:null"

See spec/list_serializer_spec.rb for more examples.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rubyslim/list_serializer.rb', line 21

def self.serialize(list)
  result = "["
  result += length_string(list.length)

  # Serialize each item in the list
  list.each do |item|
    item = "null" if item.nil?
    item = serialize(item) if item.is_a?(Array)
    item = item.to_s
    result += length_string(item.length)
    result += item + ":"
  end

  result += "]"
end