Sha256: e9013934b4a80941e7300a1ce7674754de9f40176f6f0fe32148d13501555963

Contents?: true

Size: 1.03 KB

Versions: 6

Compression:

Stored size: 1.03 KB

Contents

module CsvPiper
  module TestSupport
    class CsvMockFile
      extend Forwardable

      def self.create(headers, separator = ',')
        csv = new(headers, separator)
        yield csv if block_given?
        csv.rewind
        csv
      end

      attr_reader :headers, :io, :seperator
      delegate [:readline, :readlines, :rewind, :gets] => :io

      # Using a StringIO object instead of reading/writing files from disk
      def initialize(headers, seperator = ',')
        raise "Must have atleast one header" if headers.empty?
        @headers = headers.sort
        @seperator = seperator
        @io = StringIO.new("w+")
        io.puts(@headers.join(seperator))
      end

      def add(row_hash)
        raise "Headers don't match #{row_hash.keys - headers}" unless (row_hash.keys - headers).empty?
        row = headers.map { |key| row_hash[key] || '' }.join(seperator)
        io.puts(row)
      end

      def write_to_file(path)
        File.open(path, 'w+') do |f|
          f.write(io.read)
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
csv_piper-1.0.0 lib/csv_piper/test_support/csv_mock_file.rb
csv_piper-0.1.9 lib/csv_piper/test_support/csv_mock_file.rb
csv_piper-0.1.8 lib/csv_piper/test_support/csv_mock_file.rb
csv_piper-0.1.7 lib/csv_piper/test_support/csv_mock_file.rb
csv_piper-0.1.6 lib/csv_piper/test_support/csv_mock_file.rb
csv_piper-0.1.5 lib/csv_piper/test_support/csv_mock_file.rb