-
-
Save maasha/5c20e629b91bcb97c2ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
result | |
nil | |
nil | |
nil | |
expected | |
{"foo": 0} | |
{"bar": 1} | |
{"?": "What is this crap?"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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