Class: CsvPiper::TestSupport::CsvMockFile

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/csv_piper/test_support/csv_mock_file.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(headers, seperator = ',') ⇒ CsvMockFile

Using a StringIO object instead of reading/writing files from disk



17
18
19
20
21
22
23
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 17

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

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



13
14
15
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 13

def headers
  @headers
end

#ioObject (readonly)

Returns the value of attribute io.



13
14
15
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 13

def io
  @io
end

#seperatorObject (readonly)

Returns the value of attribute seperator.



13
14
15
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 13

def seperator
  @seperator
end

Class Method Details

.create(headers, separator = ',') {|csv| ... } ⇒ Object

Yields:

  • (csv)


6
7
8
9
10
11
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 6

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

Instance Method Details

#add(row_hash) ⇒ Object



25
26
27
28
29
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 25

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

#write_to_file(path) ⇒ Object



31
32
33
34
35
# File 'lib/csv_piper/test_support/csv_mock_file.rb', line 31

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