Class: CSVUtils::CSVReport
- Inherits:
-
Object
- Object
- CSVUtils::CSVReport
- Defined in:
- lib/csv_utils/csv_report.rb
Overview
Writes a CSV file from arrays or CSVRow objects.
Instance Attribute Summary collapse
-
#csv ⇒ CSV, #<<
readonly
Where rows are written.
-
#must_close ⇒ Boolean
readonly
Whether the report opened the file and closes it after #generate.
Instance Method Summary collapse
-
#add_headers(csv_row) ⇒ CSV, #<<
Writes the header row.
-
#append(csv_row) ⇒ CSV, #<<
(also: #<<)
Writes a row.
-
#close ⇒ void
Closes the underlying CSV.
-
#generate {|report| ... } ⇒ void
Yields the report, then closes the file if the report opened it, even when the block raises.
-
#initialize(csv, headers = nil, csv_options = {}) {|report| ... } ⇒ CSVReport
constructor
A new instance of CSVReport.
Constructor Details
#initialize(csv, headers = nil, csv_options = {}) {|report| ... } ⇒ CSVReport
Returns a new instance of CSVReport.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/csv_utils/csv_report.rb', line 21 def initialize(csv, headers = nil, = {}, &block) @csv = if csv.is_a?(String) @must_close = true opts = EncodingOptions.write() mode = opts.delete(:mode) || 'wb' CSV.open(csv, mode, **opts) else @must_close = false csv end add_headers(headers) if headers generate(&block) if block end |
Instance Attribute Details
#csv ⇒ CSV, #<< (readonly)
Returns where rows are written.
12 13 14 |
# File 'lib/csv_utils/csv_report.rb', line 12 def csv @csv end |
#must_close ⇒ Boolean (readonly)
Returns whether the report opened the file and closes it after #generate.
14 15 16 |
# File 'lib/csv_utils/csv_report.rb', line 14 def must_close @must_close end |
Instance Method Details
#add_headers(csv_row) ⇒ CSV, #<<
Writes the header row.
63 64 65 |
# File 'lib/csv_utils/csv_report.rb', line 63 def add_headers(csv_row) append(csv_row.is_a?(Array) ? csv_row : csv_row.csv_headers) end |
#append(csv_row) ⇒ CSV, #<< Also known as: <<
Writes a row.
50 51 52 53 54 55 56 57 |
# File 'lib/csv_utils/csv_report.rb', line 50 def append(csv_row) @csv << if csv_row.is_a?(Array) csv_row else csv_row.to_a end end |
#close ⇒ void
This method returns an undefined value.
Closes the underlying CSV.
69 70 71 |
# File 'lib/csv_utils/csv_report.rb', line 69 def close @csv.close end |
#generate {|report| ... } ⇒ void
This method returns an undefined value.
Yields the report, then closes the file if the report opened it, even when the block raises.
41 42 43 44 45 |
# File 'lib/csv_utils/csv_report.rb', line 41 def generate yield self ensure close if @must_close end |