Class: FlatKit::Xsv::Writer

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

Overview

Internal: Write that takes flatkit records and writes them to XSV Output

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.



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

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
    @we_write_the_header = true
  else
    @csv_options[: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.



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

def fields
  @fields
end

#header_bytesObject (readonly)

Returns the value of attribute header_bytes.



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

def header_bytes
  @header_bytes
end

Class Method Details

.default_csv_optionsObject



14
15
16
17
18
19
# File 'lib/flat_kit/xsv/writer.rb', line 14

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

.format_nameObject



10
11
12
# File 'lib/flat_kit/xsv/writer.rb', line 10

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



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

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 => e
  raise e
rescue StandardError => e
  ::FlatKit.logger.error "Error writing xsv records to #{output.name}: #{e}"
  raise ::FlatKit::Error, e
end