Class: FlatKit::Jsonl::Writer

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

Instance Attribute Summary

Attributes inherited from Writer

#count, #destination, #last_position, #output

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Writer

#close, create_writer_from_path, #current_position, #format_name

Constructor Details

#initialize(destination:) ⇒ Writer



9
10
11
# File 'lib/flat_kit/jsonl/writer.rb', line 9

def initialize(destination:)
  super
end

Class Method Details

.format_nameObject



5
6
7
# File 'lib/flat_kit/jsonl/writer.rb', line 5

def self.format_name
  ::FlatKit::Jsonl::Format.format_name
end

Instance Method Details

#write(record) ⇒ Object

write the record and return the Position the record was written



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/flat_kit/jsonl/writer.rb', line 15

def write(record)
  case record
  when FlatKit::Jsonl::Record
    write_record(record)
  when FlatKit::Record
    converted_record = ::FlatKit::Jsonl::Record.from_record(record)
    write_record(converted_record)
  else
    raise FlatKit::Error, "Unable to write records of type #{record.class}"
  end
rescue FlatKit::Error => fe
  raise fe
rescue => e
  ::FlatKit.logger.error "Error reading jsonl records from #{output.name}: #{e}"
  raise ::FlatKit::Error, e
end

#write_record(record) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/flat_kit/jsonl/writer.rb', line 32

def write_record(record)
  # the index of the record being written is the same as the count of records written so far
  record_index = @count

  # get the current output stream position to calculate bytes written
  start_offset = output.io.tell

  # enforces ending in newline if it doesn't already have one
  output.io.puts record.to_s

  ending_offset = output.io.tell
  bytes_written = (ending_offset - start_offset)

  @count += 1

  @last_position = ::FlatKit::Position.new(index: record_index,
                                           offset: start_offset,
                                           bytesize: bytes_written)

end