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

#destination

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Writer

create_writer_from_path, #format_name

Constructor Details

#initialize(destination:, fields: :auto, **csv_options) ⇒ Writer

Returns a new instance of Writer.



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

def initialize(destination:, fields: :auto, **csv_options)
  super(destination: destination)
  @fields = fields
  @output = ::FlatKit::Output.from(@destination)
  @count = 0
  @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

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

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



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

def count
  @count
end

#fieldsObject (readonly)

Returns the value of attribute fields.



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

def fields
  @fields
end

#outputObject (readonly)

Returns the value of attribute output.



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

def output
  @output
end

Class Method Details

.default_csv_optionsObject



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

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

.format_nameObject



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

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

Instance Method Details

#closeObject



55
56
57
# File 'lib/flat_kit/xsv/writer.rb', line 55

def close
  @output.close
end

#write(record) ⇒ Object



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

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