Sha256: 1225896eb21fb53a26e8a781fc8a5efcbff93d8ea2db604f30dd148b67219d3d

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
          _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.1.0 lib/recite_csv/reader/core.rb