Skip to content

Instantly share code, notes, and snippets.

@maasha
Created January 30, 2015 12:01
Show Gist options
  • Save maasha/5c20e629b91bcb97c2ee to your computer and use it in GitHub Desktop.
Save maasha/5c20e629b91bcb97c2ee to your computer and use it in GitHub Desktop.
result
nil
nil
nil
expected
{"foo": 0}
{"bar": 1}
{"?": "What is this crap?"}
#!/usr/bin/env ruby
require 'pp'
class Serializer
include Enumerable
def initialize(io, &block)
@io = io
block.call(self)
end
def <<(obj)
data = Marshal.dump(data)
@io.write([data.size].pack("I"))
@io.write(data)
end
def each
while not @io.eof?
size = @io.read(4)
raise EOFError unless size
data = @io.read(size.unpack("I").first)
yield Marshal.load(data)
end
end
end
File.open("foo.dat", 'w') do |io|
Serializer.new(io) do |s|
s << {"foo": 0}
s << {"bar": 1}
s << {"?": "What is this crap?"}
end
end
File.open("foo.dat") do |io|
Serializer.new(io) do |s|
s.each do |record|
pp record
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment