Class: HoneyFormat::CSV

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

Overview

Represents CSV.

Instance Method Summary collapse

Constructor Details

#initialize(csv, delimiter: ',', header: nil, valid_columns: :all, header_converter: ConvertHeaderValue, row_builder: nil) ⇒ CSV

Returns a new instance of CSV.

Parameters:

  • csv (String)

    string.

  • valid_columns (Array)

    valid array of symbols representing valid columns.

  • header (Array)

    optional argument for CSV header

  • row_builder (#call)

    will be called for each parsed row

Raises:


18
19
20
21
22
23
# File 'lib/honey_format/csv.rb', line 18

def initialize(csv, delimiter: ',', header: nil, valid_columns: :all, header_converter: ConvertHeaderValue, row_builder: nil)
  csv = ::CSV.parse(csv, col_sep: delimiter)
  header_row = header || csv.shift
  @header = Header.new(header_row, valid: valid_columns, converter: header_converter)
  @rows = Rows.new(csv, columns, builder: row_builder)
end

Instance Method Details

#columnsArray

Returns of column identifiers.

Returns:

  • (Array)

    of column identifiers.


31
32
33
# File 'lib/honey_format/csv.rb', line 31

def columns
  @header.columns
end

#each_row {|row| ... } ⇒ Object

Yields:

  • (row)

    block to receive the row.


42
43
44
# File 'lib/honey_format/csv.rb', line 42

def each_row
  rows.each { |row| yield(row) }
end

#headerArray

Returns of strings for sanitized header.

Returns:

  • (Array)

    of strings for sanitized header.


26
27
28
# File 'lib/honey_format/csv.rb', line 26

def header
  @header.column_names
end

#rowsArray

Returns of rows.

Returns:

  • (Array)

    of rows.

Raises:


37
38
39
# File 'lib/honey_format/csv.rb', line 37

def rows
  @rows
end

#to_csvString

Returns CSV-string representation.

Returns:

  • (String)

    CSV-string representation.


47
48
49
# File 'lib/honey_format/csv.rb', line 47

def to_csv
  header.to_csv + @rows.to_csv
end