class ArrayToCsv::CsvWriter

Public Class Methods

new(array, io, csv_lib) click to toggle source
# 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

Public Instance Methods

choose_csv_lib() click to toggle source
# 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| ... } click to toggle source
# 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
head() click to toggle source
# 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) click to toggle source
# File lib/array_to_csv/csv_writer.rb, line 41
def row_from_hash hash
  hash.values_at(*head)
end
write() click to toggle source
# 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) click to toggle source
# File lib/array_to_csv/csv_writer.rb, line 16
def write_line row
  @io.write @csv.generate_line row
end