Module: Scripto::CsvCommands
Instance Method Summary collapse
-
#csv_read(path) ⇒ Object
Read a csv from
path
. -
#csv_to_s(rows, cols: nil) ⇒ Object
Returns a string containing
rows
as a csv. -
#csv_to_stdout(rows, cols: nil) ⇒ Object
Write
rows
to $stdout as a csv. -
#csv_write(path, rows, cols: nil) ⇒ Object
Write
rows
topath
as csv.
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 22 23 24 25 26 27 |
# 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) ⇒ Object
Returns a string containing rows
as a csv. Similar to csv_write.
45 46 47 48 49 50 |
# 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) ⇒ Object
Write rows
to $stdout as a csv. Similar to csv_write.
40 41 42 |
# 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) ⇒ 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.
33 34 35 36 37 |
# 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 |