Class: BioDSL::Serializer

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/BioDSL/serializer.rb

Overview

Class for serializing and de-serializing data using Marshal.

Instance Method Summary collapse

Constructor Details

#initialize(io, &block) ⇒ Serializer

Constructor for serializer.

Parameters:

  • io (IO)

    IO object.

  • block (Proc)

    Block context.

Raises:



45
46
47
48
49
50
51
# File 'lib/BioDSL/serializer.rb', line 45

def initialize(io, &block)
  @io = io

  fail SerializerError, 'No block given' unless block

  block.call(self)
end

Instance Method Details

#<<(obj) ⇒ Object Also known as: writei

Method to write serialized data using Marshal to a given IO.

Examples:

File.open("foo.dat", 'wb') do |io|
  BioDSL::Serializer.new(io) do |s|
    s << {"foo": 0}
    s << {"bar": 1}
  end
end

Parameters:

  • obj (Object)

    Object to serialize.



64
65
66
67
68
# File 'lib/BioDSL/serializer.rb', line 64

def <<(obj)
  data = Marshal.dump(obj)
  @io.write([data.size].pack('N'))
  @io.write(data)
end

#each {|Object| ... } ⇒ Object

Iterator for reading and de-serialized data from a given IO.

Examples:

File.open("foo.dat", 'rb') do |io|
  BioDSL::Serializer.new(io) do |s|
    s.each do |record|
      puts record
    end
  end
end

Yields:

  • (Object)


84
85
86
# File 'lib/BioDSL/serializer.rb', line 84

def each
  yield next_entry until @io.eof?
end

#next_entryObject

Read next entry from serialized stream.

Returns:

  • (Object)

    Deserialized Object.



91
92
93
94
95
96
# File 'lib/BioDSL/serializer.rb', line 91

def next_entry
  size = @io.read(4)
  fail EOFError unless size
  data = @io.read(size.unpack('N').first)
  Marshal.load(data)
end