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.



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

  @row_sep = options[:row_sep] || $/
  @col_sep = options[:col_sep] || ','
  @quote_char = options[:quote_char] || '"'
  @force_quotes = options[:force_quotes] == true
  @disable_auto_quoting = options[:disable_auto_quoting] == true
  @value_converters = options[:value_converters] || {}
  @map_all_keys = @value_converters.has_key?(:_all)
  @mapped_keys = @value_converters.keys - [:_all]

  @discover_headers = true
  if options.has_key?(:discover_headers)
    @discover_headers = options[:discover_headers] == true # ⚠️ this option should not be exposed
  else
    @discover_headers = !(options.has_key?(:map_headers) || options.has_key?(:headers))
  end

  @headers = []
  @headers = options[:headers] if options.has_key?(:headers)
  @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+')
  @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

#finalizeObject



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