Class: ArrayToCsv::CsvWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/array_to_csv/csv_writer.rb

Instance Method Summary collapse

Constructor Details

#initialize(array, io, csv_lib) ⇒ CsvWriter

Returns a new instance of CsvWriter.



3
4
5
6
# File 'lib/array_to_csv/csv_writer.rb', line 3

def initialize array, io, csv_lib
  @array, @io = array, io
  @csv = csv_lib || choose_csv_lib
end

Instance Method Details

#choose_csv_libObject



45
46
47
48
49
50
51
# File 'lib/array_to_csv/csv_writer.rb', line 45

def choose_csv_lib
  if RUBY_VERSION =~ /^1\.8/
    FasterCSV
  else
    CSV
  end
end

#each_row {|head| ... } ⇒ Object

Yields:



20
21
22
23
24
25
# File 'lib/array_to_csv/csv_writer.rb', line 20

def each_row
  yield head
  @array.each do |hash|
    yield row_from_hash hash
  end
end

#headObject



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/array_to_csv/csv_writer.rb', line 27

def head
  @head_from_array ||= [].tap do |keys|
    seen_keys = {}
    @array.each do |hash|
      hash.keys.each do |key|
        unless seen_keys[key]
          seen_keys[key] = true
          keys << key
        end
      end
    end
  end
end

#row_from_hash(hash) ⇒ Object



41
42
43
# File 'lib/array_to_csv/csv_writer.rb', line 41

def row_from_hash hash
  hash.values_at(*head)
end

#writeObject



8
9
10
11
12
13
14
# File 'lib/array_to_csv/csv_writer.rb', line 8

def write
  each_row do |row|
    write_line row
  end
  @io.close
  nil
end

#write_line(row) ⇒ Object



16
17
18
# File 'lib/array_to_csv/csv_writer.rb', line 16

def write_line row
  @io.write @csv.generate_line row
end