Class: CSVUtils::CSVReport

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv, headers = nil, csv_options = {}, &block) ⇒ CSVReport

Returns a new instance of CSVReport.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/csv_utils/csv_report.rb', line 7

def initialize(csv, headers = nil, csv_options = {}, &block)
  @csv =
    if csv.is_a?(String)
      @must_close = true
      mode = csv_options.delete(:mode) || 'wb'
      CSV.open(csv, mode, **csv_options)
    else
      @must_close = false
      csv
    end

  add_headers(headers) if headers

  generate(&block) if block
end

Instance Attribute Details

#csvObject (readonly)

Returns the value of attribute csv.



4
5
6
# File 'lib/csv_utils/csv_report.rb', line 4

def csv
  @csv
end

#must_closeObject (readonly)

Returns the value of attribute must_close.



4
5
6
# File 'lib/csv_utils/csv_report.rb', line 4

def must_close
  @must_close
end

Instance Method Details

#add_headers(csv_row) ⇒ Object



38
39
40
# File 'lib/csv_utils/csv_report.rb', line 38

def add_headers(csv_row)
  append(csv_row.is_a?(Array) ? csv_row : csv_row.csv_headers)
end

#append(csv_row) ⇒ Object Also known as: <<



28
29
30
31
32
33
34
35
# File 'lib/csv_utils/csv_report.rb', line 28

def append(csv_row)
  @csv <<
    if csv_row.is_a?(Array)
      csv_row
    else
      csv_row.to_a
    end
end

#closeObject



42
43
44
# File 'lib/csv_utils/csv_report.rb', line 42

def close
  @csv.close
end

#generate {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



23
24
25
26
# File 'lib/csv_utils/csv_report.rb', line 23

def generate
  yield self
  close if @must_close
end