Module: Hakoy::FileAppender::Csv

Extended by:
Csv
Included in:
Csv
Defined in:
lib/hakoy/file_appender/csv.rb

Defined Under Namespace

Modules: DuplicatesFilter

Instance Method Summary collapse

Instance Method Details

#call(file_path, rows_hash, opts = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hakoy/file_appender/csv.rb', line 25

def call(file_path, rows_hash, opts={})
  uid_key     = opts.fetch(:uid_key) { 'id' }
  file_exists = File.exists?(file_path)
  rows_hash   = Array.wrap(rows_hash)

  return if rows_hash.empty?

  CSV.open(file_path, 'a') do |to_file|
    append_row_hash_values = -> (row_hash) do
      append_to_csv_file(to_file, row_hash.values)
    end

    if file_exists
      when_not_a_duplicate(file_path, rows_hash, uid_key, &append_row_hash_values)
    else
      # Add header for new file and no need to check duplicates
      header_hash = rows_hash[0].keys
      append_to_csv_file to_file, header_hash
      rows_hash.each(&append_row_hash_values)
    end
  end
end