Class: FlatKit::Xsv::Writer

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

Instance Attribute Summary collapse

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:, fields: :auto, **csv_options) ⇒ Writer

Returns a new instance of Writer.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/flat_kit/xsv/writer.rb', line 18

def initialize(destination:, fields: :auto, **csv_options)
  super(destination: destination)
  @fields = fields
  @we_write_the_header = nil
  @csv_options = Writer.default_csv_options.dup

  if @fields == :auto then
    @we_write_the_header = true
  else
    @csv_options.merge!(headers: fields)
    @we_write_the_header = false
  end

  @header_bytes = 0
  @csv_options.merge!(csv_options)
  @csv = CSV.new(output.io, **@csv_options)
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



4
5
6
# File 'lib/flat_kit/xsv/writer.rb', line 4

def fields
  @fields
end

#header_bytesObject (readonly)

Returns the value of attribute header_bytes.



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

def header_bytes
  @header_bytes
end

Class Method Details

.default_csv_optionsObject



11
12
13
14
15
16
# File 'lib/flat_kit/xsv/writer.rb', line 11

def self.default_csv_options
  {
    headers: nil,
    write_headers: true
  }
end

.format_nameObject



7
8
9
# File 'lib/flat_kit/xsv/writer.rb', line 7

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

Instance Method Details

#write(record) ⇒ Object

write the record and return the Position the record was written

In the case of the header being written automatcially, the Postion returned is the position of the reocrd, not the header



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/flat_kit/xsv/writer.rb', line 41

def write(record)
  case record
  when FlatKit::Xsv::Record
    write_record(record)
  when FlatKit::Record
    converted_record = ::FlatKit::Xsv::Record.from_record(record, ordered_fields: @fields)
    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