Sha256: 740eec9b7d09e3bb728155fa89dac43d33a8bc438cf71a2dbef30ac64f2a1c20

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

# frozen_string_literal: true

require "csv"

module ReciteCSV
  module Reader
    module Core
      include Enumerable

      attr_reader :file, :file_options, :csv_options

      def initialize(file, file_options: {}, **options)
        @file = file
        @file_options = file_options
        @csv_options = options.merge(self.class::DEFAULT_CSV_OPTIONS)
      end

      def each(&block)
        if block_given?
          _each(&block)
        else
          self.to_enum
        end
      end

      private

      def _each(&block)
        f = _open
        begin
          _foreach(f, &block)
        ensure
          f.close if self.file.is_a?(::String)
        end
      end

      def _open
        return self.file unless self.file.is_a?(::String)

        args = Array(self.file_options)
        if args.last.is_a?(::Hash)
          args = args.dup
          kw_args = args.pop
          ::File.open(self.file, *args, **kw_args)
        else
          ::File.open(self.file, *args)
        end
      end

      def _foreach(file)
        ::CSV.new(file, **self.csv_options).each do |raw_row|
          yield self.class::Row.new(raw_row)
        end
        self
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
recite_csv-2.0.0 lib/recite_csv/reader/core.rb