Class: IOStreams::Line::Writer

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

Instance Attribute Summary collapse

Attributes inherited from Writer

#output_stream

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Writer

file, open

Constructor Details

#initialize(output_stream, delimiter: $/, original_file_name: nil) ⇒ Writer

A delimited stream writer that will write to the supplied output stream.

The output stream will have the encoding of data written to it. To change the output encoding, use IOStreams::Encode::Writer.

Parameters

output_stream
  The output stream that implements #write

delimiter: [String]
  Add the specified delimiter after every record when writing it
  to the output stream
  Default: OS Specific. Linux: "\n"


27
28
29
30
# File 'lib/io_streams/line/writer.rb', line 27

def initialize(output_stream, delimiter: $/, original_file_name: nil)
  super(output_stream)
  @delimiter = delimiter
end

Instance Attribute Details

#delimiterObject (readonly)

Returns the value of attribute delimiter.



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

def delimiter
  @delimiter
end

Class Method Details

.stream(output_stream, **args) {|new(output_stream, **args)| ... } ⇒ Object

Write a line at a time to a stream.

Yields:



7
8
9
10
11
12
# File 'lib/io_streams/line/writer.rb', line 7

def self.stream(output_stream, **args)
  # Pass-through if already a line writer
  return yield(output_stream) if output_stream.is_a?(self.class)

  yield new(output_stream, **args)
end

Instance Method Details

#<<(data) ⇒ Object

Write a line to the output stream

Example:

IOStreams.path('a.txt').writer(:line) do |stream|
  stream << 'first line' << 'second line'
end


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

def <<(data)
  write(data)
  self
end

#write(data) ⇒ Object

Write a line to the output stream followed by the delimiter. Returns [Integer] the number of bytes written.

Example:

IOStreams.path('a.txt').writer(:line) do |stream|
  count = stream.write('first line')
  puts "Wrote #{count} bytes to the output file, including the delimiter"
end


51
52
53
# File 'lib/io_streams/line/writer.rb', line 51

def write(data)
  output_stream.write(data.to_s + delimiter)
end