Class: CSV::Writer

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

Overview

Note: Don’t use this class directly. This is an internal class.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output, options) ⇒ Writer

Returns a new instance of Writer.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/csv/writer.rb', line 18

def initialize(output, options)
  @output = output
  @options = options
  @lineno = 0
  @fields_converter = nil
  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



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

def headers
  @headers
end

#linenoObject (readonly)

A CSV::Writer receives an output, prepares the header, format and output. It allows us to write new rows in the object and rewind it.



15
16
17
# File 'lib/csv/writer.rb', line 15

def lineno
  @lineno
end

Instance Method Details

#<<(row) ⇒ Object

Adds a new row



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/csv/writer.rb', line 33

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

Winds back to the beginning



61
62
63
64
# File 'lib/csv/writer.rb', line 61

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