module OOCSV

Constants

CSVEntry

A struct representing a single line in a CSV file.

Public Instance Methods

read(string) click to toggle source

Read a CSV string into an array of CSVEntries. @param string [String] The CSV. @return [Array<Struct::CSVEntry>] An array of CSVEntries representing the CSV provided.

# File lib/oocsv.rb, line 37
def read(string)
  lines = string.split("\n")
  header = lines[0]
  attributes = header.split(',').map! { |v| v.to_sym }
  # Struct.new('CSVEntry', *attributes)
  ret = []
  lines.drop(1).each do |line|
    values = line.split(',')
    opts = {}
    values.each_with_index do |val, idx|
      opts[attributes[idx]] = val
    end
    ret << Struct::CSVEntry.new(opts)
  end

  ret
end
write(objects = []) click to toggle source

Turns an array of CSVEntries (see read) into a String. @param objects [Array<Struct::CSVEntry>] The array of structs. @return [String] The CSV representing the array given.

# File lib/oocsv.rb, line 58
def write(objects = [])
  return '' if objects.empty?
  str = ''
  vars = objects[0].instance_variables.select! { |v| v != :@i_expect_that_nobody_will_use_this_name }.map { |v| v }
  str << vars.map { |i| i[1..-1] }.join(',')
  str << "\n"
  objects.each_with_index do |obj, obj_indx|
    vars.each_with_index do |var, var_indx|
      val = obj.instance_variable_get(var)
      str << val
      str << ',' if var_indx != vars.size - 1
    end
    str << "\n" if obj_indx != objects.size - 1
  end

  str
end