Class: SmarterCSV::Writer
- Inherits:
-
Object
- Object
- SmarterCSV::Writer
- Defined in:
- lib/smarter_csv/writer.rb
Instance Method Summary collapse
-
#<<(data) ⇒ Object
this can be called many times in order to append lines to the csv file.
- #finalize ⇒ Object
-
#initialize(file_path, options = {}) ⇒ Writer
constructor
A new instance of Writer.
Constructor Details
#initialize(file_path, options = {}) ⇒ Writer
Returns a new instance of Writer.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/smarter_csv/writer.rb', line 41 def initialize(file_path, = {}) @options = @row_sep = [:row_sep] || $/ # Defaults to system's row separator. RFC4180 "\r\n" @col_sep = [:col_sep] || ',' @quote_char = [:quote_char] || '"' @force_quotes = [:force_quotes] == true @discover_headers = true # defaults to true if .has_key?(:discover_headers) # passing in the option overrides the default behavior @discover_headers = [:discover_headers] == true else # disable discover_headers when headers are given explicitly @discover_headers = !(.has_key?(:map_headers) || .has_key?(:headers)) end @headers = [] # start with empty headers @headers = [:headers] if .has_key?(:headers) # unless explicitly given @headers = [:map_headers].keys if .has_key?(:map_headers) && !.has_key?(:headers) @map_headers = [:map_headers] || {} @output_file = File.open(file_path, 'w+') # hidden state: @temp_file = Tempfile.new('tempfile', '/tmp') @quote_regex = Regexp.union(@col_sep, @row_sep, @quote_char) end |
Instance Method Details
#<<(data) ⇒ Object
this can be called many times in order to append lines to the csv file
68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/smarter_csv/writer.rb', line 68 def <<(data) case data when Hash process_hash(data) when Array data.each { |item| self << item } when NilClass # ignore else raise InvalidInputData, "Invalid data type: #{data.class}. Must be a Hash or an Array." end end |
#finalize ⇒ Object
81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/smarter_csv/writer.rb', line 81 def finalize # Map headers if :map_headers option is provided mapped_headers = @headers.map { |header| @map_headers[header] || header } mapped_headers = mapped_headers.map{|x| escape_csv_field(x)} if @force_quotes @temp_file.rewind @output_file.write(mapped_headers.join(@col_sep) + @row_sep) @output_file.write(@temp_file.read) @output_file.flush @output_file.close @temp_file.delete end |