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.



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

def csv_read(path)
  rows = if /\.gz$/.match?(path)
    Zlib::GzipReader.open(path) do
      CSV.new(_1).read
    end
  else
    CSV.read(path, encoding: "bom|utf-8")
  end

  keys = rows.shift.map(&:to_sym)
  klass = Struct.new(*keys)
  rows.map { klass.new(*_1) }
end

#csv_to_s(rows, cols: nil) ⇒ Object

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



39
40
41
42
43
44
# File 'lib/scripto/csv_commands.rb', line 39

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

#csv_to_stdout(rows, cols: nil) ⇒ Object

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



34
35
36
# File 'lib/scripto/csv_commands.rb', line 34

def csv_to_stdout(rows, cols: nil)
  CSV($stdout) { csv_write0(_1, rows, 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.



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

def csv_write(path, rows, cols: nil)
  atomic_write(path) do |tmp|
    CSV.open(tmp.path, "wb") { csv_write0(_1, rows, cols:) }
  end
end