Class: FlatKit::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/flat_kit/writer.rb

Overview

Public: The base class for all format writers.

A format writer will only write those Records, and on that, only those of its own format.

It must implement a #write methods takes a Record. It can convert the record to one matching its own format if it whishes. But it should in any case check the Record format to make sure it matches

See the Xsv::Writer and Jsonl::Writer for examples.

Direct Known Subclasses

Jsonl::Writer, Xsv::Writer

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(destination:) ⇒ Writer

Returns a new instance of Writer.



24
25
26
27
28
29
# File 'lib/flat_kit/writer.rb', line 24

def initialize(destination:)
  @destination = destination
  @output = ::FlatKit::Output.from(@destination)
  @count = 0
  @last_position = nil
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



16
17
18
# File 'lib/flat_kit/writer.rb', line 16

def count
  @count
end

#destinationObject (readonly)

Returns the value of attribute destination.



16
17
18
# File 'lib/flat_kit/writer.rb', line 16

def destination
  @destination
end

#last_positionObject (readonly)

Returns the value of attribute last_position.



16
17
18
# File 'lib/flat_kit/writer.rb', line 16

def last_position
  @last_position
end

#outputObject (readonly)

Returns the value of attribute output.



16
17
18
# File 'lib/flat_kit/writer.rb', line 16

def output
  @output
end

Class Method Details

.create_writer_from_path(path:, fallback:, reader_format:) ⇒ Object



18
19
20
21
22
# File 'lib/flat_kit/writer.rb', line 18

def self.create_writer_from_path(path:, fallback:, reader_format:)
  fallback = reader_format if fallback == "auto"
  format   = ::FlatKit::Format.for_with_fallback!(path: path, fallback: fallback)
  format.writer.new(destination: path)
end

Instance Method Details

#closeObject



48
49
50
# File 'lib/flat_kit/writer.rb', line 48

def close
  output.close
end

#current_positionObject



35
36
37
38
39
# File 'lib/flat_kit/writer.rb', line 35

def current_position
  ::FlatKit::Position.new(index: @count,       # since this hasn't been written yet its the right index
                          offset: output.tell,
                          bytesize: 0)         # nothing has been written yet
end

#format_nameObject



31
32
33
# File 'lib/flat_kit/writer.rb', line 31

def format_name
  self.class.format_name
end

#write(record) ⇒ Object

The write method MUST return a Position object detailing the location the record was written in the output stream.

Raises:

  • (NotImplementedError)


44
45
46
# File 'lib/flat_kit/writer.rb', line 44

def write(record)
  raise NotImplementedError, "#{self.class} needs to implement #write that returns Position"
end