Last active
August 29, 2015 14:00
-
-
Save michellemhey/11404086 to your computer and use it in GitHub Desktop.
This is the file I'm apparently supposed to add the code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
# http://www.sebgrosjean.com/en/news/2012/1 | |
require 'csv' # adds a .to_csv method to Array instances | |
class Array | |
BOM = "\xEF\xBB\xBF" #Byte Order Mark UTF-8 | |
alias old_to_csv to_csv #keep reference to original to_csv method | |
def to_csv(options = Hash.new) | |
options = options.merge(:force_quotes => true) | |
# override only if first element actually has as_csv method | |
return old_to_csv(options) unless self.first.respond_to? :as_csv | |
# use keys from first row as header columns | |
out = first.as_csv.keys.collect{|k| k.to_s.titleize }.to_csv(options) | |
# collect all entries as CSV, ensure that no line break is present within values | |
self.each { |r| out << r.as_csv.values.to_csv(options).gsub(/\r?\n/, ' ').strip! + "\n" } | |
# Force encoding to UTF-16LE and add Byte Order Mark for Excel compatibility | |
(BOM + out).force_encoding("UTF-8") | |
end | |
def to_tsv(options={}) | |
to_csv(options.merge(:col_sep => "\t")) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment