Class: Philiprehberger::CsvKit::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/csv_kit/writer.rb

Overview

Generates CSV output from arrays of hashes or arrays.

Defined Under Namespace

Classes: StreamWriter

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(headers:) ⇒ Writer

Returns a new instance of Writer.

Parameters:

  • headers (Array<Symbol, String>)

    column headers



8
9
10
# File 'lib/philiprehberger/csv_kit/writer.rb', line 8

def initialize(headers:)
  @headers = headers.map(&:to_sym)
end

Class Method Details

.stream(io, headers:, dialect: nil) {|StreamWriter| ... } ⇒ IO

Stream CSV rows incrementally to an IO object without buffering.

Parameters:

  • io (IO)

    writable IO object

  • headers (Array<Symbol, String>)

    column headers

  • dialect (Symbol, Hash, nil) (defaults to: nil)

    CSV dialect preset or custom options

Yields:

Returns:

  • (IO)

    the IO object



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

def self.stream(io, headers:, dialect: nil, &block)
  writer = StreamWriter.new(io, headers: headers, dialect: dialect)
  block.call(writer)
  io
end

Instance Method Details

#write(rows) ⇒ String

Write rows to a CSV string.

Parameters:

  • rows (Array<Hash, Array>)

    data rows

Returns:

  • (String)

    CSV string



29
30
31
# File 'lib/philiprehberger/csv_kit/writer.rb', line 29

def write(rows)
  generate_csv(rows, StringIO.new).string
end

#write_to(rows, io) ⇒ IO

Write rows to an IO object.

Parameters:

  • rows (Array<Hash, Array>)

    data rows

  • io (IO)

    writable IO

Returns:

  • (IO)

    the IO object



38
39
40
41
# File 'lib/philiprehberger/csv_kit/writer.rb', line 38

def write_to(rows, io)
  generate_csv(rows, io)
  io
end