Class: Origen::Utility::CSV

Inherits:
Object show all
Defined in:
lib/origen/utility/csv_data.rb

Overview

A class to handle the parsing of Comma Separated Value (CSV) input data Field names are indicated on first line of file, separated by comma Field values are indicated on all lines after first line of file, separated by comma All lines must have same number of fields names and values

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ CSV

Supply a path to the CSV file, this should be a relative path from the top level of your project workspace (Origen.root)



10
11
12
# File 'lib/origen/utility/csv_data.rb', line 10

def initialize(file)
  @file = file
end

Instance Method Details

#fieldsObject

Parses the data and returns only the field values (keys) defined in the first line of the file opens file but only reads first line

Example

csv = CSV.new("/path/to/data.csv")
field_names = csv.fields


53
54
55
# File 'lib/origen/utility/csv_data.rb', line 53

def fields
  extract_csv_data(field_names_only: true)
end

#num_fieldsObject

Number of fields in file



58
59
60
# File 'lib/origen/utility/csv_data.rb', line 58

def num_fields
  fields.length
end

#parse(options = {}) ⇒ Object

Parses the CSV file and returns an array of hashes where each hash represents one line of data. Hash keys obtained from first line of field names. Optionally if block supplied, it will return a single line from CSV file at a time

Example

csv = CSV.new("/path/to/data.csv")

Process data yourself
data = csv.parse
data.each do |dataline|
   dataline.keys.each do |key|
     print "Key: #{key}, Value: #{dataline[key]}\n"
   end
end

Let parse process data (not much diff)
csv.parse do |dataline|
   dataline.keys.each do |key|
     print "Key: #{key}, Value: #{dataline[key]}\n"
   end
end


35
36
37
38
39
40
41
42
43
44
# File 'lib/origen/utility/csv_data.rb', line 35

def parse(options = {})
  csv_data = extract_csv_data(options)
  if block_given? # doesn't do much at this point
    csv_data.each do |dataset|
      yield dataset
    end
  else
    csv_data
  end
end

#valid_fields?(check_fields = []) ⇒ Boolean

Checks fields to ensure they exist Input: array of fields expected

Returns:

  • (Boolean)


64
65
66
# File 'lib/origen/utility/csv_data.rb', line 64

def valid_fields?(check_fields = [])
  fields.eql?(check_fields)
end