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.



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

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.



14
15
16
# File 'lib/flat_kit/writer.rb', line 14

def destination
  @destination
end

#last_positionObject (readonly)

Returns the value of attribute last_position.



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

def last_position
  @last_position
end

#outputObject (readonly)

Returns the value of attribute output.



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

def output
  @output
end

Class Method Details

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



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

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



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

def close
  output.close
end

#current_positionObject



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

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



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

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)


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

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