Class: CSVRow

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

Overview

Represents a single CSV row.

Instance Method Summary collapse

Constructor Details

#initialize(file, len_or_headers) ⇒ CSVRow

Returns a new instance of CSVRow.



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/csvgen.rb', line 58

def initialize(file, len_or_headers)
  @file = file
  @cols = []
  @headers = {}
  if len_or_headers.is_a? Numeric then
    self.length = len_or_headers
  else
    self.headers = len_or_headers
    self.length = len_or_headers.length
  end
end

Instance Method Details

#[]=(idx, val) ⇒ Object

Set value by numeric index or by header (should be a value from header array)



92
93
94
95
96
97
98
99
100
# File 'lib/csvgen.rb', line 92

def []=(idx, val)
  if idx.is_a? Numeric then
    @cols[idx] = val
  else
    hidx = @headers[idx]
    raise "Header field #{idx.inspect} not found" if hidx.nil?
    @cols[hidx] = val
  end
end

#headers=(hdrs) ⇒ Object

Set the header array



71
72
73
74
75
# File 'lib/csvgen.rb', line 71

def headers=(hdrs)
  hdrs.each_with_index do |h, ii|
    @headers[h] = ii
  end
end

#length=(n) ⇒ Object

Set the fixed column length, for when you don’t have headers



86
87
88
# File 'lib/csvgen.rb', line 86

def length=(n)
  @cols = (0..(n - 1)).map { |idx| @cols[idx] || nil }
end

#push(*args) ⇒ Object

Append columns



78
79
80
81
82
83
# File 'lib/csvgen.rb', line 78

def push(*args)
  args.each do |x|
    @cols.push(x)
  end
  self
end

#to_sObject



102
103
104
# File 'lib/csvgen.rb', line 102

def to_s
  @cols.collect { |c| @file.enquote(c) }.join(@file.sep)
end