Chem::FormatWriter(T)
Inherits IO::Wrapper
Declares a common interface for writing an object encoded in a file format.
Including types must implement the #encode_entry(T) protected
method, where the type variable T indicates the encoded type.
Including types will behave like an IO wrapper via the IO::Wrapper
mixin, which provides convenience constructors. Initialization
arguments are gathered from the designated #initialize method
looked up on concrete types at compilation time. The underlying IO
can be accessed through the @io instance variable.
struct Foo
getter num : Int32
getter str : String
def initialize(@num : Int32, @str : String); end
end
class Foo::Writer
include Chem::FormatWriter(Foo)
def encode_entry(foo : Foo) : Nil
@io.puts foo.num
@io.puts foo.str
end
end
io = IO::Memory.new
writer = Foo::Writer.new io
writer.written? # => false
writer << Foo.new(123, "bar")
io.to_s # => "123\nbar\n"
writer.written? # => true
writer << Foo.new(456, "baz") # raises IO::Error (an entry was already written)
writer.close
writer << Foo.new(789, "foo") # raises IO::Error (closed IO)
Constants
File open mode. May be overriden by including types.
Instance methods
Writes the given object into the IO. Raises IO::Error if the
IO is closed or if an entry was already written.
Writes a formatted string to the enclosed IO. For details on the
format string, see top-level sprintf.
Writes a formatted string followed by a newline to the enclosed
IO. For details on the format string, see top-level sprintf.