Class: IOStreams::Row::Writer

Inherits:
Writer
  • Object
show all
Defined in:
lib/io_streams/row/writer.rb

Overview

Example:

IOStreams.path("file.csv").writer(:array) do |stream|
  stream << ['name', 'address', 'zipcode']
  stream << ['Jack', 'Somewhere', 12345]
  stream << ['Joe', 'Lost', 32443]
end

Instance Attribute Summary

Attributes inherited from Writer

#output_stream

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Writer

open

Constructor Details

#initialize(line_writer, columns: nil, **args) ⇒ Writer

Create a Tabular writer that takes individual rows as arrays.

Parameters

line_writer: [#<<]
  Anything that accepts a line / record at a time when #<< is called on it.

format: [Symbol]
  :csv, :hash, :array, :json, :psv, :fixed

For all other parameters, see Tabular::Header.new


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/io_streams/row/writer.rb', line 39

def initialize(line_writer, columns: nil, **args)
  unless line_writer.respond_to?(:<<)
    raise(ArgumentError, 'Stream must be a IOStreams::Line::Writer or implement #<<')
  end

  @tabular     = IOStreams::Tabular.new(columns: columns, **args)
  @line_writer = line_writer

  # Render header line when `columns` is supplied.
  line_writer << @tabular.render_header if columns && @tabular.requires_header?
end

Class Method Details

.file(file_name, original_file_name: file_name, delimiter: $/, **args, &block) ⇒ Object

When writing to a file also add the line writer stream



23
24
25
26
27
# File 'lib/io_streams/row/writer.rb', line 23

def self.file(file_name, original_file_name: file_name, delimiter: $/, **args, &block)
  IOStreams::Line::Writer.file(file_name, original_file_name: original_file_name, delimiter: delimiter) do |io|
    yield new(io, **args, &block)
  end
end

.stream(line_writer, original_file_name: nil, **args) {|new(line_writer, **args)| ... } ⇒ Object

Write a record from an Array at a time to a stream.

Note:

  • The supplied stream must already be a line stream, or a stream that responds to :<<

Yields:

  • (new(line_writer, **args))


15
16
17
18
19
20
# File 'lib/io_streams/row/writer.rb', line 15

def self.stream(line_writer, original_file_name: nil, **args)
  # Pass-through if already a row writer
  return yield(line_writer) if line_writer.is_a?(self.class)

  yield new(line_writer, **args)
end

Instance Method Details

#<<(array) ⇒ Object

Supply a hash or an array to render

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
59
60
61
62
# File 'lib/io_streams/row/writer.rb', line 52

def <<(array)
  raise(ArgumentError, 'Must supply an Array') unless array.is_a?(Array)

  if @tabular.header?
    # If header (columns) was not supplied as an argument, assume first line is the header.
    @tabular.header.columns = array
    @line_writer << @tabular.render_header
  else
    @line_writer << @tabular.render(array)
  end
end