lib/io_streams/row/reader.rb in iostreams-0.20.3 vs lib/io_streams/row/reader.rb in iostreams-1.0.0.beta
- old
+ new
@@ -1,31 +1,23 @@
module IOStreams
module Row
# Converts each line of an input stream into an array for every line
- class Reader
- # Read a line as an Array at a time from a file or stream.
- def self.open(file_name_or_io,
- delimiter: nil,
- buffer_size: 65_536,
- file_name: nil,
- encoding: nil,
- encode_cleaner: nil,
- encode_replace: nil,
- **args)
- if file_name_or_io.is_a?(String)
- IOStreams.line_reader(file_name_or_io,
- delimiter: delimiter,
- buffer_size: buffer_size,
- file_name: file_name,
- encoding: encoding,
- encode_cleaner: encode_cleaner,
- encode_replace: encode_replace
- ) do |io|
- yield new(io, file_name: file_name, **args)
- end
- else
- yield new(file_name_or_io, **args)
+ class Reader < IOStreams::Reader
+ # Read a line as an Array at a time from a stream.
+ # Note:
+ # - The supplied stream _must_ already be a line stream, or a stream that responds to :each
+ def self.stream(line_reader, original_file_name: nil, **args, &block)
+ # Pass-through if already a row reader
+ return block.call(line_reader) if line_reader.is_a?(self.class)
+
+ yield new(line_reader, **args)
+ end
+
+ # When reading from a file also add the line reader stream
+ def self.file(file_name, original_file_name: file_name, delimiter: $/, **args)
+ IOStreams::Line::Reader.file(file_name, original_file_name: original_file_name, delimiter: delimiter) do |io|
+ yield new(io, **args)
end
end
# Create a Tabular reader to return the stream rows as arrays.
#
@@ -35,17 +27,21 @@
#
# format: [Symbol]
# :csv, :hash, :array, :json, :psv, :fixed
#
# For all other parameters, see Tabular::Header.new
- def initialize(delimited, cleanse_header: true, **args)
+ def initialize(line_reader, cleanse_header: true, **args)
+ unless line_reader.respond_to?(:each)
+ raise(ArgumentError, "Stream must be a IOStreams::Line::Reader or implement #each")
+ end
+
@tabular = IOStreams::Tabular.new(**args)
- @delimited = delimited
+ @line_reader = line_reader
@cleanse_header = cleanse_header
end
def each
- @delimited.each do |line|
+ @line_reader.each do |line|
if @tabular.header?
columns = @tabular.parse_header(line)
@tabular.cleanse_header! if @cleanse_header
yield columns
else