Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting CSV headers to be case insensitive in Ruby

I have a ruby import to DB process that checks header titles against an array called headers. As it stands right now, those headers must be typed exactly the same as they appear in the array. I would like for them to be accepted regardless if they are upper or lowercase.

CSV.foreach(FILE, encoding:'iso-8859-1:utf-8', headers: true, skip_blanks: true) do |row| 

# check the header row, make sure all are acceptable
if count == 0
  row.headers.each do |header|
    if (!headers.include? header) and !header.nil? and header != ""
      log.error "#{header} is not a valid header"
       exit
    end
  end
 end

Currently accepts: "Ast_A" But does not accept: "ast_a" I have tried code from Convert hash keys to lowercase -- Ruby Beginner to no avail. My question is how do I make the .csv import header row case insensitive during the import?

like image 807
Stinga B Avatar asked Feb 20 '18 21:02

Stinga B


1 Answers

You can provide a header_converter object that respond to the call method and receive the header string as an argument, such as a lambda or a proc:

converter = lambda { |header| header.downcase }
CSV.foreach([...], headers: true, header_converters: converter, [...]) do |row|

With this, all headers will be parsed in lower case. You can then compare it to a lower case version of your local variable headers.

like image 66
MrYoshiji Avatar answered Sep 26 '22 05:09

MrYoshiji