Class: Hocsv

Inherits:
Object
  • Object
show all
Defined in:
lib/hocsv.rb,
lib/hocsv/version.rb

Overview

Converts an array of hashes into csv format and creates a csv file

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, filename = "hocsv.csv") ⇒ Hocsv

Creates an instance with data and filename attributes. ‘data’ parameter recieves an array of hashses or a local variable storing an array of hashses. ‘filename’ parameter recieves a string; defaults to ‘hocsv.csv’ Invokes to_hocsv

Raises:



18
19
20
21
22
23
24
25
26
# File 'lib/hocsv.rb', line 18

def initialize(data, filename="hocsv.csv")
  # 'data=' Returns the value of the data sent to the 'data' parameter
  self.data = data

  # Returns the value of the 'filename' parameter
  self.filename = filename
  raise InvalidDataError.new if (!data.is_a?(Array)) || (data.empty?.eql?(TRUE)) || (!data.any? {|obj| obj.respond_to?(:keys)}) || (!filename.is_a?(String)) || (filename.empty?.eql?(TRUE))
  to_hocsv
end

Instance Attribute Details

#dataObject

‘data’ attribute takes data in the form of an array of hashses ‘filename’ attribute takes a string as the name of the file to be created.



11
12
13
# File 'lib/hocsv.rb', line 11

def data
  @data
end

#filenameObject

‘data’ attribute takes data in the form of an array of hashses ‘filename’ attribute takes a string as the name of the file to be created.



11
12
13
# File 'lib/hocsv.rb', line 11

def filename
  @filename
end

Instance Method Details

#to_hocsvObject

Creates .csv file and converts data to csv



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hocsv.rb', line 29

def to_hocsv
  # adds. .csv to the end of the filename if not present
  filename.concat('.csv') if !filename.include?(".csv")

  #Places uniq keys into an array
  headers = data.flat_map(&:keys).uniq
  # Opens a new csv file in read and write mode with the provided file name or the default file name; adds column formatting
  CSV.open(filename, "w+b", col_sep: ', ') do |csv|

    # pushes headers to the file
    csv <<  headers

    data.each do |hash|
    #Retrieves values at a keys location, and inserts empty space when no value is present
      csv << hash.values_at(*headers)
    end
  end
end