Class: Comparator::CompareCSV

Inherits:
Object
  • Object
show all
Defined in:
lib/comparator/csv.rb

Defined Under Namespace

Classes: CSVHeaderMissMatchError, CSVInitializeError

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ CompareCSV

Returns a new instance of CompareCSV.



18
19
20
21
22
23
24
# File 'lib/comparator/csv.rb', line 18

def initialize(*args)
  if args.length == 2
    @file_name = args
  else
    raise CSVInitializeError
  end
end

Instance Method Details

#csv_file_comparatorObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/comparator/csv.rb', line 37

def csv_file_comparator
  fixed_file = file_encoder(@file_name[0])
  comparing_file = file_encoder(@file_name[1])
  difference_hash = {}

  fixed_file_header = fixed_file.headers
  comparing_file_header = comparing_file.headers

  fixed_file_column = fixed_file.by_col
  comparing_file_column = comparing_file.by_col

  # check if both file has the same header
  if fixed_file_header.sort == comparing_file_header.sort
    # ensure header and column of both file are not swapped
    zip_index = 0
    fixed_file_column.zip(comparing_file_column).each do |fixed_column_data, compare_column_data|
      difference_hash[fixed_file_header[zip_index]] = fixed_column_data[1].difference(compare_column_data[1])
      zip_index += 1
    end
  else
    raise CSVHeaderMissMatchError
  end
  difference_hash
end

#does_it_work?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/comparator/csv.rb', line 26

def does_it_work?
  true
end

#file_encoder(file_path) ⇒ Object



30
31
32
33
34
35
# File 'lib/comparator/csv.rb', line 30

def file_encoder(file_path)
  # reference: https://stackoverflow.com/questions/5163339/write-and-read-a-file-with-utf-8-encoding
  options = { headers: true }.freeze
  encode_file = File.open(file_path, "r:UTF-8")
  CSV.parse(encode_file, options)
end