lib/duracloud/tsv.rb in duracloud-client-0.2.0 vs lib/duracloud/tsv.rb in duracloud-client-0.3.0
- old
+ new
@@ -1,32 +1,54 @@
require "csv"
module Duracloud
module TSV
- # @return [CSV::Table]
+
def csv
- @csv ||= CSV::Table.new([]).tap do |csv|
- header_line, rows = tsv.split(/\r?\n/, 2)
- headers = header_line.split("\t").map { |h| h.downcase.gsub(/-/, "_") }
- header_row = CSV::Row.new(headers, headers, true)
- csv << header_row
- rows.split(/\r?\n/).each do |row|
- csv << row.split("\t")
- end
- end
+ @csv ||= CSV.new(tsv, csv_options)
end
- # @return [Enumerator] rows as hashes
def rows
- Enumerator.new do |e|
- csv.by_row!.each do |row|
- next if row.header_row?
- e << row.to_hash
- end
+ @rows ||= Enumerator.new do |e|
+ table.each { |row| e << row.to_hash }
end
end
+ def table
+ csv.rewind
+ csv.read
+ ensure
+ csv.rewind
+ end
+
def tsv
- raise NotImplementedError, "Including module must implement `tsv`."
+ @tsv
end
+
+ def load_tsv(io_or_str)
+ @tsv = io_or_str
+ end
+
+ def load_tsv_file(path)
+ load_tsv(File.new(path, "rb"))
+ end
+
+ def to_s
+ tsv.to_s
+ end
+
+ private
+
+ def csv_options
+ { col_sep: "\t",
+ quote_char: "`",
+ headers: true,
+ header_converters: header_converters,
+ }
+ end
+
+ def header_converters
+ lambda { |h| h.downcase.gsub(/-/, "_") }
+ end
+
end
end