Class: GoodData::Helpers::Csv
- Defined in:
- lib/gooddata/helpers/csv_helper.rb
Class Method Summary collapse
-
.ammend_line(filename, data) ⇒ Object
Ammend a hash to CSV in a smart manner.
-
.read(opts) ⇒ Object
Read data from CSV.
-
.read_as_hash(filename) ⇒ Object
Read data from csv as an array of hashes with symbol keys and parsed integers.
-
.write(opts, &_block) ⇒ Object
Write data to CSV.
Class Method Details
.ammend_line(filename, data) ⇒ Object
Ammend a hash to CSV in a smart manner
75 76 77 78 79 80 81 82 83 84 |
# File 'lib/gooddata/helpers/csv_helper.rb', line 75 def ammend_line(filename, data) current_data = read_as_hash(filename) data_to_write = (current_data << data).map(&:sort).map { |r| Hash[r] } FileUtils.mkpath(filename.split('/')[0...-1].join('/')) CSV.open(filename, 'w', write_headers: true, headers: data_to_write.first.keys) do |csv| data_to_write.each do |d| csv << d.values end end end |
.read(opts) ⇒ Object
Read data from CSV
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/gooddata/helpers/csv_helper.rb', line 20 def read(opts) path = opts[:path] res = [] line = 0 CSV.foreach(path) do |row| line += 1 next if opts[:header] && line == 1 if block_given? data = yield row else data = row end res << data if data end res end |
.read_as_hash(filename) ⇒ Object
Read data from csv as an array of hashes with symbol keys and parsed integers
44 45 46 47 48 49 50 51 52 |
# File 'lib/gooddata/helpers/csv_helper.rb', line 44 def read_as_hash(filename) res = [] return res unless File.exist? filename CSV.parse(File.read(filename), headers: true, header_converters: :symbol, converters: :integer).map do |row| res << row.to_hash end res end |
.write(opts, &_block) ⇒ Object
Write data to CSV
58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/gooddata/helpers/csv_helper.rb', line 58 def write(opts, &_block) path = opts[:path] header = opts[:header] data = opts[:data] CSV.open(path, 'w') do |csv| csv << header unless header.nil? data.each do |entry| res = yield entry csv << res if res end end end |