Class: Tabula::Writers::CSVWriter

Inherits:
Writer
  • Object
show all
Defined in:
lib/tabula/writers/csv_writer.rb

Overview

Writes tables in CSV format

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Writer

write

Constructor Details

#initialize(separator: ',', quote_char: '"', force_quotes: false, **options) ⇒ CSVWriter

Returns a new instance of CSVWriter.

Parameters:

  • separator (String) (defaults to: ',') —

    field separator (default: comma)

  • quote_char (String) (defaults to: '"') —

    quote character (default: double quote)

  • force_quotes (Boolean) (defaults to: false) —

    always quote fields (default: false)



12
13
14
15
16
17
# File 'lib/tabula/writers/csv_writer.rb', line 12

def initialize(separator: ',', quote_char: '"', force_quotes: false, **options)
  super(**options)
  @separator = separator
  @quote_char = quote_char
  @force_quotes = force_quotes
end

Class Method Details

.to_string(tables, **options) ⇒ String

Write tables to a string

Parameters:

  • tables (Array<Table>) —

    tables to write

Returns:

  • (String) —

    CSV formatted output



41
42
43
44
45
46
# File 'lib/tabula/writers/csv_writer.rb', line 41

def self.to_string(tables, **options)
  require 'stringio'
  io = StringIO.new
  new(**options).write(tables, io)
  io.string
end

Instance Method Details

#write(tables, io) ⇒ Object

Write tables to an IO object

Parameters:

  • tables (Array<Table>) —

    tables to write

  • io (IO) —

    output destination



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tabula/writers/csv_writer.rb', line 22

def write(tables, io)
  csv_options = {
    col_sep: @separator,
    quote_char: @quote_char,
    force_quotes: @force_quotes
  }

  tables.each_with_index do |table, idx|
    # Add blank line between tables
    io.puts if idx.positive?

    csv = CSV.new(io, **csv_options)
    table.to_a.each { |row| csv << row }
  end
end