Class: SmarterCSV::Writer
- Inherits:
-
Object
- Object
- SmarterCSV::Writer
- Defined in:
- lib/smarter_csv/writer.rb
Instance Method Summary collapse
- #<<(data) ⇒ Object
- #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.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/smarter_csv/writer.rb', line 44 def initialize(file_path, = {}) @options = @row_sep = [:row_sep] || $/ @col_sep = [:col_sep] || ',' @quote_char = [:quote_char] || '"' @force_quotes = [:force_quotes] == true @disable_auto_quoting = [:disable_auto_quoting] == true @value_converters = [:value_converters] || {} @map_all_keys = @value_converters.has_key?(:_all) @mapped_keys = @value_converters.keys - [:_all] @discover_headers = true if .has_key?(:discover_headers) @discover_headers = [:discover_headers] == true # ⚠️ this option should not be exposed else @discover_headers = !(.has_key?(:map_headers) || .has_key?(:headers)) end @headers = [] @headers = [:headers] if .has_key?(:headers) @headers = [:map_headers].keys if .has_key?(:map_headers) && !.has_key?(:headers) @map_headers = [:map_headers] || {} @output_file = File.open(file_path, 'w+') @temp_file = Tempfile.new('tempfile', '/tmp') @quote_regex = Regexp.union(@col_sep, @row_sep, @quote_char) end |
Instance Method Details
#<<(data) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/smarter_csv/writer.rb', line 73 def <<(data) case data when Hash process_hash(data) when Array data.each { |item| self << item } when NilClass # ignore else # :nocov: raise InvalidInputData, "Invalid data type: #{data.class}. Must be a Hash or an Array." # :nocov: end end |
#finalize ⇒ Object
88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/smarter_csv/writer.rb', line 88 def finalize 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 |