module Chem::FormatWriter(T)

Overview

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)

Included Modules

Direct including types

Defined in:

chem/format_writer.cr

Constant Summary

FILE_MODE = "w"

File open mode. May be overriden by including types.

Instance Method Summary

Instance methods inherited from module IO::Wrapper

close close, closed? : Bool closed?, sync_close : Bool sync_close, sync_close=(sync_close : Bool) sync_close=

Instance Method Detail

def <<(obj : T) : Nil #

Writes the given object into the IO. Raises IO::Error if the IO is closed or if an entry was already written.


[View source]
def format(str : String, *args, **options) : Nil #

Writes a formatted string to the enclosed IO. For details on the format string, see top-level sprintf.


[View source]
def formatl(str : String, *args, **options) : Nil #

Writes a formatted string followed by a newline to the enclosed IO. For details on the format string, see top-level sprintf.


[View source]
def written? : Bool #

Returns true if an object was already written.


[View source]