Module: Scripto::CsvCommands

Included in:
Scripto, Main
Defined in:
lib/scripto/csv_commands.rb

Instance Method Summary collapse

Instance Method Details

#csv_read(path) ⇒ Object

Read a csv from path. Returns an array of Structs, using the keys from the csv header row.



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/scripto/csv_commands.rb', line 8

def csv_read(path)
  lines = if path =~ /\.gz$/
    Zlib::GzipReader.open(path) do |f|
      CSV.new(f).read
    end
  else
    CSV.read(path)
  end
  keys = lines.shift.map(&:to_sym)
  klass = Struct.new(*keys)
  lines.map { |i| klass.new(*i) }
end

#csv_to_s(rows, cols: nil) ⇒ Object

Returns a string containing rows as a csv. Similar to csv_write.



41
42
43
44
45
46
# File 'lib/scripto/csv_commands.rb', line 41

def csv_to_s(rows, cols: nil)
  string = ""
  f = CSV.new(StringIO.new(string))
  csv_write0(f, rows, cols: cols)
  string
end

#csv_to_stdout(rows, cols: nil) ⇒ Object

Write rows to $stdout as a csv. Similar to csv_write.



36
37
38
# File 'lib/scripto/csv_commands.rb', line 36

def csv_to_stdout(rows, cols: nil)
  CSV($stdout) { |f| csv_write0(f, rows, cols: cols) }
end

#csv_write(path, rows, cols: nil) ⇒ Object

Write rows to path as csv. Rows can be an array of hashes, Structs, OpenStructs, or anything else that responds to to_h. The keys from the first row are used as the csv header. If cols is specified, it will be used as the column keys instead.



25
26
27
28
29
30
31
32
33
# File 'lib/scripto/csv_commands.rb', line 25

def csv_write(path, rows, cols: nil)
  begin
    tmp = "/tmp/_scripto_csv.csv"
    CSV.open(tmp, "wb") { |f| csv_write0(f, rows, cols: cols) }
    mv(tmp, path)
  ensure
    rm_if_necessary(tmp)
  end
end