Class: SmarterCSV::Writer

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

Instance Method Summary collapse

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 = {})
  @options = options

  @row_sep = options[:row_sep] || $/ # Defaults to system's row separator. RFC4180 "\r\n"
  @col_sep = options[:col_sep] || ','
  @quote_char = options[:quote_char] || '"'
  @force_quotes = options[:force_quotes] == true
  @discover_headers = true # defaults to true
  if options.has_key?(:discover_headers)
    # passing in the option overrides the default behavior
    @discover_headers = options[:discover_headers] == true
  else
    # disable discover_headers when headers are given explicitly
    @discover_headers = !(options.has_key?(:map_headers) || options.has_key?(:headers))
  end
  @headers = [] # start with empty headers
  @headers = options[:headers] if options.has_key?(:headers) # unless explicitly given
  @headers = options[:map_headers].keys if options.has_key?(:map_headers) && !options.has_key?(:headers)
  @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

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

#finalizeObject



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