module Chem::FormatReader(T)

Overview

Declares a common interface for reading an object encoded in a file format.

Including types must implement the #decode_entry : T protected method, where the type variable T indicates the encoded type. Upon parsing issues, including types are expected to raise a ParseException exception.

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::Reader
  include Chem::FormatReader(Foo)

  def decode_entry : Foo
    Foo.new num: @io.read_line.to_i, str: @io.read_line
  end
end

io = IO::Memory.new "123\nbar\n"
reader = Foo::Reader.new io
reader.read? # => false
obj = reader.read_entry
obj.num           # => 123
obj.str           # => "bar"
reader.read?      # => true
reader.read_entry # raises IO::Error (entry was already read)
reader.close
reader.read_entry # raises IO::Error (closed IO)

Included Modules

Direct including types

Defined in:

chem/format_reader.cr

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 read? : Bool #

Returns true if this encoded object was already read.


[View source]
def read_entry : T #

Reads the encoded object of type T from the IO. Raises IO::Error if the reader is closed or the encoded object has been already read, or ParseException if an object cannot be read.


[View source]