Sha256: bc489b26e368a4e0d52367523b5d0d78daf691e5e663017328e2c3adfbf2b435

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

module IOStreams
  module Record
    # Converts each line of an input stream into hash for every row
    class Reader
      include Enumerable

      # Read a record as a Hash at a time from a file or stream.
      def self.open(file_name_or_io, delimiter: nil, buffer_size: 65536, 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,
                                encoding:       encoding,
                                encode_cleaner: encode_cleaner,
                                encode_replace: encode_replace
          ) do |io|
            yield new(io, file_name: file_name_or_io, **args)
          end
        else
          yield new(file_name_or_io, **args)
        end
      end

      # 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
      def initialize(delimited, cleanse_header: true, **args)
        @tabular        = IOStreams::Tabular.new(**args)
        @delimited      = delimited
        @cleanse_header = cleanse_header
      end

      def each
        @delimited.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
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
iostreams-0.16.2 lib/io_streams/record/reader.rb
iostreams-0.16.1 lib/io_streams/record/reader.rb
iostreams-0.16.0 lib/io_streams/record/reader.rb