Class: IOStreams::Record::Reader

Inherits:
IOStreams::Reader show all
Includes:
Enumerable
Defined in:
lib/io_streams/record/reader.rb

Overview

Converts each line of an input stream into hash for every row

Instance Attribute Summary

Attributes inherited from IOStreams::Reader

#input_stream

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from IOStreams::Reader

open

Constructor Details

#initialize(line_reader, cleanse_header: true, **args) ⇒ Reader

Create a Tabular reader to return the stream as Hash records Parse a delimited data source.

Parameters

delimited: [#each]
  Anything that returns one line / record at a time when #each is called on it.

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

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


35
36
37
38
39
40
41
42
43
# File 'lib/io_streams/record/reader.rb', line 35

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)
  @line_reader    = line_reader
  @cleanse_header = cleanse_header
end

Class Method Details

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

When reading from a file also add the line reader stream



18
19
20
21
22
# File 'lib/io_streams/record/reader.rb', line 18

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

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

Read a record at a time from a line stream Note:

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

Yields:

  • (new(line_reader, **args))


10
11
12
13
14
15
# File 'lib/io_streams/record/reader.rb', line 10

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

  yield new(line_reader, **args)
end

Instance Method Details

#eachObject



45
46
47
48
49
50
51
52
53
54
# File 'lib/io_streams/record/reader.rb', line 45

def each
  @line_reader.each do |line|
    if @tabular.header?
      @tabular.parse_header(line)
      @tabular.cleanse_header! if @cleanse_header
    else
      yield @tabular.record_parse(line)
    end
  end
end