Class: IOStreams::Line::Writer
- Inherits:
-
Object
- Object
- IOStreams::Line::Writer
- Defined in:
- lib/io_streams/line/writer.rb
Instance Attribute Summary collapse
-
#delimiter ⇒ Object
readonly
Returns the value of attribute delimiter.
Class Method Summary collapse
-
.open(file_name_or_io, **args) ⇒ Object
Write a line at a time to a file or stream.
Instance Method Summary collapse
-
#<<(data) ⇒ Object
Write a line to the output stream.
-
#initialize(output_stream, delimiter: $/) ⇒ Writer
constructor
A delimited stream writer that will write to the supplied output stream.
-
#write(data) ⇒ Object
Write a line to the output stream followed by the delimiter.
Constructor Details
#initialize(output_stream, delimiter: $/) ⇒ 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"
28 29 30 31 |
# File 'lib/io_streams/line/writer.rb', line 28 def initialize(output_stream, delimiter: $/) @output_stream = output_stream @delimiter = delimiter end |
Instance Attribute Details
#delimiter ⇒ Object (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
.open(file_name_or_io, **args) ⇒ Object
Write a line at a time to a file or stream
7 8 9 10 11 12 13 |
# File 'lib/io_streams/line/writer.rb', line 7 def self.open(file_name_or_io, **args) if file_name_or_io.is_a?(String) IOStreams::File::Writer.open(file_name_or_io) { |io| yield new(io, **args) } else yield new(file_name_or_io, **args) end end |
Instance Method Details
#<<(data) ⇒ Object
Write a line to the output stream
Example:
IOStreams.line_writer('a.txt') do |stream|
stream << 'first line' << 'second line'
end
39 40 41 42 |
# File 'lib/io_streams/line/writer.rb', line 39 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.line_writer('a.txt') do |stream|
count = stream.write('first line')
puts "Wrote #{count} bytes to the output file, including the delimiter"
end
52 53 54 |
# File 'lib/io_streams/line/writer.rb', line 52 def write(data) @output_stream.write(data.to_s + delimiter) end |