Module: OOCSV

Defined in:
lib/oocsv.rb

Defined Under Namespace

Classes: CSVEntry

Class Method Summary collapse

Class Method Details

.read(string) ⇒ Array<Struct::CSVEntry>

Read a CSV string into an array of CSVEntries.

Parameters:

  • string (String)

    The CSV.

Returns:

  • (Array<Struct::CSVEntry>)

    An array of CSVEntries representing the CSV provided.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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 = []) ⇒ String

Turns an array of CSVEntries (see #read) into a String.

Parameters:

  • objects (Array<Struct::CSVEntry>) (defaults to: [])

    The array of structs.

Returns:

  • (String)

    The CSV representing the array given.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 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