Class: SmarterCSV::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/smarter_csv/writer.rb

Overview

IMPORTANT NOTES:

* Data hashes could contain strings or symbols as keys.
  Make sure to use the correct form when specifying headers manually,
  in combination with the :discover_headers option

Instance Method Summary collapse

Constructor Details

#initialize(file_path, options = {}) ⇒ Writer

Returns a new instance of Writer.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/smarter_csv/writer.rb', line 39

def initialize(file_path, options = {})
  @options = options
  @discover_headers = options.has_key?(:discover_headers) ? (options[:discover_headers] == true) : true
  @headers = options[:headers] || []
  @row_sep = options[:row_sep] || "\n" # RFC4180 "\r\n"
  @col_sep = options[:col_sep] || ','
  @quote_char = '"'
  @force_quotes = options[:force_quotes] == true
  @map_headers = options[: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



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/smarter_csv/writer.rb', line 54

def <<(data)
  case data
  when Hash
    process_hash(data)
  when Array
    data.each { |item| self << item }
  when NilClass
    # ignore
  else
    raise ArgumentError, "Invalid data type: #{data.class}. Must be a Hash or an Array."
  end
end

#finalizeObject



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/smarter_csv/writer.rb', line 67

def finalize
  # Map headers if :map_headers option is provided
  mapped_headers = @headers.map { |header| @map_headers[header] || header }

  @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