Module: FlatFile::CSV

Defined in:
lib/flat_file/csv.rb

Class Method Summary collapse

Class Method Details

.from_file(filepath) ⇒ Array<Hash>

Read a CSV file and return its contents as an array of hashes.

Parameters:

  • filepath (String)

    Path to the CSV file.

Returns:

  • (Array<Hash>)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/flat_file/csv.rb', line 10

def self.from_file(filepath)
  rows = []
  begin
    ::CSV.foreach(filepath, headers: true) do |row|
      rows.append(row)
    end
    return rows
  rescue StandardError => e
    # if defined?(Rails)
    #   Rails.logger.error({
    #     message: "Error reading CSV file",
    #     filepath: filepath,
    #     error: e,
    #   })
    # end
    return rows
  end
end

.from_stream(data) ⇒ Array<Hash>

Read a CSV stream and return its contents as an array of hashes.

Parameters:

  • data (String, IO)

    Stream of CSV data.

Returns:

  • (Array<Hash>)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/flat_file/csv.rb', line 33

def self.from_stream(data)
  rows = []
  begin
    ::CSV.new(data, headers: true).each do |row|
      rows.append(row)
    end
    return rows
  rescue StandardError => e
    # if defined?(Rails)
    #   Rails.logger.error({
    #     message: "Error reading CSV data",
    #     error: e,
    #   })
    # end
    return rows
  end
end