Class: CSV::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/csv/writer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output, options) ⇒ Writer

Returns a new instance of Writer.



13
14
15
16
17
18
19
20
21
22
# File 'lib/csv/writer.rb', line 13

def initialize(output, options)
  @output = output
  @options = options
  @lineno = 0
  prepare
  if @options[:write_headers] and @headers
    self << @headers
  end
  @fields_converter = @options[:fields_converter]
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



11
12
13
# File 'lib/csv/writer.rb', line 11

def headers
  @headers
end

#linenoObject (readonly)

Returns the value of attribute lineno.



10
11
12
# File 'lib/csv/writer.rb', line 10

def lineno
  @lineno
end

Instance Method Details

#<<(row) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/csv/writer.rb', line 24

def <<(row)
  case row
  when Row
    row = row.fields
  when Hash
    row = @headers.collect {|header| row[header]}
  end

  @headers ||= row if @use_headers
  @lineno += 1

  row = @fields_converter.convert(row, nil, lineno) if @fields_converter

  converted_row = row.collect do |field|
    quote(field)
  end
  line = converted_row.join(@column_separator) + @row_separator
  if @output_encoding
    line = line.encode(@output_encoding)
  end
  @output << line

  self
end

#rewindObject



49
50
51
52
# File 'lib/csv/writer.rb', line 49

def rewind
  @lineno = 0
  @headers = nil if @options[:headers].nil?
end