Class: Ethel::Targets::CSV

Inherits:
Ethel::Target show all
Defined in:
lib/ethel/targets/csv.rb

Instance Method Summary collapse

Methods inherited from Ethel::Target

#prepare

Constructor Details

#initialize(options) ⇒ CSV

Returns a new instance of CSV.



4
5
6
7
8
9
10
# File 'lib/ethel/targets/csv.rb', line 4

def initialize(options)
  super

  @options = options
  @fields = []
  @rows = []
end

Instance Method Details

#add_field(field) ⇒ Object



12
13
14
# File 'lib/ethel/targets/csv.rb', line 12

def add_field(field)
  @fields << field
end

#add_row(row) ⇒ Object



16
17
18
# File 'lib/ethel/targets/csv.rb', line 16

def add_row(row)
  @rows << row
end

#dataObject



39
40
41
42
43
# File 'lib/ethel/targets/csv.rb', line 39

def data
  if @options[:string]
    @data
  end
end

#flushObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ethel/targets/csv.rb', line 20

def flush
  headers = @fields.collect(&:name)
  csv_options = {
    :headers => headers,
    :write_headers => true
  }
  csv =
    if @options[:file]
      ::CSV.open(@options[:file], 'wb', csv_options)
    elsif @options[:string]
      @data = ""
      ::CSV.new(@data, csv_options)
    end
  @rows.each do |row|
    csv << row.values_at(*headers)
  end
  csv.close
end