Class: IOStreams::Record::Writer
- Defined in:
- lib/io_streams/record/writer.rb
Overview
Instance Attribute Summary
Attributes inherited from Writer
Class Method Summary collapse
-
.file(file_name, original_file_name: file_name, delimiter: $/, **args, &block) ⇒ Object
When writing to a file also add the line writer stream.
-
.stream(line_writer, original_file_name: nil, **args) {|new(line_writer, **args)| ... } ⇒ Object
Write a record as a Hash at a time to a stream.
Instance Method Summary collapse
- #<<(hash) ⇒ Object
-
#initialize(line_writer, columns: nil, **args) ⇒ Writer
constructor
Create a Tabular writer that takes individual Parse a delimited data source.
Methods inherited from Writer
Constructor Details
#initialize(line_writer, columns: nil, **args) ⇒ Writer
Create a Tabular writer that takes individual Parse a delimited data source.
Parameters
delimited: [#<<]
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
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/io_streams/record/writer.rb', line 37 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
20 21 22 23 24 |
# File 'lib/io_streams/record/writer.rb', line 20 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 as a Hash at a time to a stream. Note:
-
The supplied stream must already be a line stream, or a stream that responds to :<<
12 13 14 15 16 17 |
# File 'lib/io_streams/record/writer.rb', line 12 def self.stream(line_writer, original_file_name: nil, **args) # Pass-through if already a record writer return yield(line_writer) if line_writer.is_a?(self.class) yield new(line_writer, **args) end |
Instance Method Details
#<<(hash) ⇒ Object
49 50 51 52 53 54 55 56 57 58 |
# File 'lib/io_streams/record/writer.rb', line 49 def <<(hash) raise(ArgumentError, '#<< only accepts a Hash argument') unless hash.is_a?(Hash) if @tabular.header? # Extract header from the keys from the first row when not supplied above. @tabular.header.columns = hash.keys @line_writer << @tabular.render_header end @line_writer << @tabular.render(hash) end |