Validating Ruby CSV format

Asked

Viewed 45 times

0

I need to validate the format of the CSV file in pure Ruby, the validation is for the header. I created this code, but it is not working. What am I doing wrong? I’m new to Ruby.

require 'csv'
csv_file= CSV.read('Relatorio_de_Campanhas.csv')

expected_header = ["Campanha", "Visualizações"]
$csv_error = true if expected_header && csv_file

def check_header(expected_header,csv_file)
  header = CSV.open(csv_file, 'r') { |csv| csv.first }
  valid_csv = true
  (0..header.size - 1).each { |i|
    if header[i] != expected_header[i]
      valid_csv = false
    end
  }

  if !valid_csv
    $csv_error = "
    Header:
     #{header}
    Expected Header:
     #{expected_header} "
  end
  valid_csv
end

check_header(expected_header, csv_file)

1 answer

0

The method open in CSV expects to receive the name of a file as the first parameter, but you are passing the content returned by CSV.read('Relatorio_de_Campanhas.csv'), which is not the file name.

When changing CSV.open(csv_file, 'r') for CSV.open("Relatorio_de_Campanhas.csv", 'r'), the code can be executed without errors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.