Class: Ralphttp::CsvExport

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(header = nil) ⇒ CsvExport

Public - Start the class and pass the header fields along with the data

header - Array holding the header field values

Example:

csv = Ralphttp::CsvExport( %w(Time Latency Response) )

Returns nil



13
14
15
16
# File 'lib/ralphttp/csvexport.rb', line 13

def initialize(header = nil)
  @data = []
  add_header(header)
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



4
5
6
# File 'lib/ralphttp/csvexport.rb', line 4

def data
  @data
end

#headerObject

Returns the value of attribute header.



3
4
5
# File 'lib/ralphttp/csvexport.rb', line 3

def header
  @header
end

Instance Method Details

#add_header(header) ⇒ Object

Public - Add header description for the CSV fields

header - Array of field data

Retuns nil



60
61
62
# File 'lib/ralphttp/csvexport.rb', line 60

def add_header(header)
  @header =  header.join(',') if header.kind_of?(Array)
end

#add_row(row) ⇒ Object

Public - Add a row to the data Array

row - Array holding field values

Returns nil



69
70
71
# File 'lib/ralphttp/csvexport.rb', line 69

def add_row(row)
  @data << row.join(',')  if row.kind_of?(Array)
end

Public - Print out the CSV data

Example:

csv = Ralphttp::CsvExport.new
csv.add_header(%w(Title Name Location)
csv.add_row(%(CEO Khan Nebula))
csv.print
# => Title,Name,Location
# => CEO,Khan,Nebula

Returns String list in CSV format



29
30
31
32
33
34
35
# File 'lib/ralphttp/csvexport.rb', line 29

def print
  @data.unshift(@header)

  @data.each do |d|
    puts d
  end
end

#write(file) ⇒ Object

Public - Write the parsed data to a specified file

file - String File location

Example:

csv.write('/tmp/file.csv')

Returns nil



45
46
47
48
49
50
51
52
53
# File 'lib/ralphttp/csvexport.rb', line 45

def write(file)
  @data.unshift(@header)
  storage = File.open(file, 'w')

  @data.each do |d|
    storage.write("#{d}\n")
  end
  storage.close
end