Class: Ralphttp::CsvExport
- Inherits:
-
Object
- Object
- Ralphttp::CsvExport
- Defined in:
- lib/ralphttp/csvexport.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#header ⇒ Object
Returns the value of attribute header.
Instance Method Summary collapse
-
#add_header(header) ⇒ Object
Public - Add header description for the CSV fields.
-
#add_row(row) ⇒ Object
Public - Add a row to the data Array.
-
#initialize(header = nil) ⇒ CsvExport
constructor
Public - Start the class and pass the header fields along with the data.
-
#print ⇒ Object
Public - Print out the CSV data.
-
#write(file) ⇒ Object
Public - Write the parsed data to a specified file.
Constructor Details
#initialize(header = nil) ⇒ CsvExport
13 14 15 16 |
# File 'lib/ralphttp/csvexport.rb', line 13 def initialize(header = nil) @data = [] add_header(header) end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
4 5 6 |
# File 'lib/ralphttp/csvexport.rb', line 4 def data @data end |
#header ⇒ Object
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 |
#print ⇒ Object
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 |