Class: CSV2API::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/csv2api/parser.rb

Overview

Contains methods for parsing CSV files

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ CSV2API::CSVParse

Passes file argument down to parser

Parameters:

  • file (File, IO)

    file to parse



14
15
16
# File 'lib/csv2api/parser.rb', line 14

def initialize(file)
  @file = parse(file)
end

Instance Attribute Details

#fileString (readonly)

Returns parsed csv file.

Returns:

  • (String)

    parsed csv file



9
10
11
# File 'lib/csv2api/parser.rb', line 9

def file
  @file
end

Instance Method Details

#allArray<Hash>

Returns an array of hashes from csv file

Returns:

  • (Array<Hash>)

    csv data



32
33
34
# File 'lib/csv2api/parser.rb', line 32

def all
  file.to_a.map { |row| empty?(row.to_hash) }.compact
end

#empty?(hash) ⇒ Hash<Symbol>

Returns hash unless it’s empty

Parameters:

  • hash (Hash<Symbol>)

Returns:

  • (Hash<Symbol>)

    hash



39
40
41
# File 'lib/csv2api/parser.rb', line 39

def empty?(hash)
  hash unless hash.empty?
end

#parse(csv_file) ⇒ CSV

Parses csv file

Parameters:

  • csv_file (File, IO)

    csv file to parse

Returns:

  • (CSV)

    parsed csv data



21
22
23
24
25
26
27
28
# File 'lib/csv2api/parser.rb', line 21

def parse(csv_file)
  CSV::Converters[:blank_to_nil] = lambda do |field|
    field && field.empty? ? nil : field
  end

  CSV.new(csv_file,
          headers: true, header_converters: :symbol, converters: :all)
end