Class: Uncsv

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/uncsv.rb,
lib/uncsv/row.rb,
lib/uncsv/rows.rb,
lib/uncsv/config.rb,
lib/uncsv/header.rb,
lib/uncsv/version.rb,
lib/uncsv/key_normalizer.rb

Overview

Parses CSV data and iterates through it

Accepts a String, IO, or file, and outputs CSV rows. The rows can be iterated over with each. Uncsv is also Enumerable, so all of those built-in Ruby methods also work with it, including map, reduce, select, etc.

Defined Under Namespace

Classes: Config, Header, KeyNormalizer, Row, Rows

Constant Summary collapse

VERSION =

The current Uncsv library version

'1.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, opts = {}) {|config| ... } ⇒ Uncsv

Create a new Uncsv parser

Parameters:

  • data (String, IO)

    The input CSV data to parse

  • opts (Hash) (defaults to: {})

    A hash of configuration options. See Uncsv::Config#initialize.

Yields:

  • An optional block for setting configuration options.

Yield Parameters:

  • config (Config)

    The configuration object.



28
29
30
31
32
# File 'lib/uncsv.rb', line 28

def initialize(data, opts = {})
  @config = Config.new(opts)
  yield @config if block_given?
  @csv = CSV.new(data, @config.csv_opts)
end

Class Method Details

.open(filename, opts = {}) {|config| ... } ⇒ Object

Create a new Uncsv parser from a file

Parameters:

  • filename (String)

    The path of the file to open

  • opts (Hash) (defaults to: {})

    A hash of configuration options. See Uncsv::Config#initialize.

Yields:

  • An optional block for setting configuration options.

Yield Parameters:

  • config (Config)

    The configuration object.



40
41
42
# File 'lib/uncsv.rb', line 40

def self.open(filename, opts = {}, &block)
  new(File.open(filename, 'rb'), opts, &block)
end

Instance Method Details

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

Iterate over each data row of the CSV

Yields:

  • A block to run for each row

Yield Parameters:

  • row (Row)

    A row object

Returns:

  • (Enumerator)

    An enumerator over each row



49
50
51
# File 'lib/uncsv.rb', line 49

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

#headerArray

Get an array of the headers

Ordered from left to right

Returns:

  • (Array)

    An array of the header rows



58
59
60
# File 'lib/uncsv.rb', line 58

def header
  rows.header
end