module Scripto::CsvCommands
Public Instance Methods
csv_read(path)
click to toggle source
Read a csv from path
. Returns an array of Structs, using the keys from the csv header row.
# File lib/scripto/csv_commands.rb, line 9 def csv_read(path) lines = begin if path =~ /\.gz$/ Zlib::GzipReader.open(path) do |f| CSV.new(f).read end else encoding = 'bom|utf-8' if RUBY_VERSION >= "2.6.0" CSV.read(path, encoding: encoding) else CSV.read(path, "r:#{encoding}") end end end keys = lines.shift.map(&:to_sym) klass = Struct.new(*keys) lines.map { |i| klass.new(*i) } end
csv_to_s(rows, cols: nil)
click to toggle source
Returns a string containing rows
as a csv. Similar to csv_write.
# File lib/scripto/csv_commands.rb, line 45 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)
click to toggle source
Write rows
to $stdout as a csv. Similar to csv_write.
# File lib/scripto/csv_commands.rb, line 40 def csv_to_stdout(rows, cols: nil) CSV($stdout) { |f| csv_write0(f, rows, cols: cols) } end
csv_write(path, rows, cols: nil)
click to toggle source
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.
# File lib/scripto/csv_commands.rb, line 33 def csv_write(path, rows, cols: nil) atomic_write(path) do |tmp| CSV.open(tmp.path, 'wb') { |f| csv_write0(f, rows, cols: cols) } end end