Class: Uncsv::Header

Inherits:
Object
  • Object
show all
Defined in:
lib/uncsv/header.rb

Overview

A parsed CSV header.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(headers, config = nil) ⇒ Header

Create a new Header object

Parameters:

  • headers (Array<Array<String>>)

    An array of header row values

  • config (Config) (defaults to: nil)

    Configuration options. Default options if nil.



10
11
12
13
14
# File 'lib/uncsv/header.rb', line 10

def initialize(headers, config = nil)
  @headers = headers
  @config = config || Config.new
  @to_a = nil
end

Class Method Details

.parse!(csv, config) ⇒ OpenStruct

Parse headers from a CSV

Parameters:

  • csv (CSV)

    A CSV object.

  • config (Config)

    Configuration options. Default options if nil.

Returns:

  • (OpenStruct)

    An object with the methods header, index, and rows. header is the Uncsv::Header object. index is the next CSV row index. rows is an array of the skipped rows including the header rows.



53
54
55
56
57
58
59
60
61
62
# File 'lib/uncsv/header.rb', line 53

def parse!(csv, config)
  index = config.header_rows.empty? ? 0 : (config.header_rows.max + 1)
  rows = read_rows(csv, index)
  headers = config.header_rows.map { |i| rows[i] }
  OpenStruct.new(
    header: new(headers, config),
    index: index,
    rows: rows
  )
end

Instance Method Details

#each {|row| ... } ⇒ Enumerator

Iterate over each header field

Yields:

  • A block to run for each header field

Yield Parameters:

  • row (String)

    A header field

Returns:

  • (Enumerator)

    An enumerator over header field



21
22
23
# File 'lib/uncsv/header.rb', line 21

def each(&block)
  to_a.each(&block)
end

#to_aArray

Get an array of parsed header fields

The header fields are cached, so consecutive calls to this method return the same array.

Returns:

  • (Array)

    The array of header fields



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/uncsv/header.rb', line 31

def to_a
  @to_a ||= begin
    headers = nil_empty(@headers)
    headers = square(headers)
    headers = normalize(headers) if @config.normalize_headers
    headers = expand(headers)
    combined = combine(headers)
    combined = unique(combined) if @config.unique_headers
    combined
  end
end