2

An instrument I use outputs a CSV file of data, but I cannot control the column names. I would like to change the header row before importing the data (without editing the raw CSV file) so that I can use the following code to import into my database:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    Foo.create! row.to_hash
  end
end  

How do I completely replace the header row with one of my own?

2 Answers 2

8

You can use the :header_converters option with a lambda that uses a lookup table.

convert = {"from" => "to", "bad" => "good"}
CSV.foreach(file.path, headers: true, header_converters: lambda { |name| convert[name] }) do |row|
...

If the transformations you want to make to the names are simpler, you can just apply changes to the name in the lambda.

You can use the method in Ivan's answer if you want to completely rename the headers.

Sign up to request clarification or add additional context in comments.

4 Comments

One issue, Other headers except convert will becoming empty
Try something like convert[name] || "Placeholder" in the lambda. This will default the label to "Placeholder" if it's not in the lookup hash.
i am using new that might be creating this issue, as I only want to change the given one and all other should remain same CSV.new(body, headers: true, header_converters: lambda { |name| convert[name].to_sym }, converters: :all)
Work Around: lambda { |name| (convert[name] || name).to_sym } so the final version is: csv = CSV.new(body, headers: true, header_converters: lambda { |name| (convert[name] || name).to_sym }, converters: :all)
0

You can pass array of custom column names instead of a simple true value to headers option:

CSV.foreach(file.path, headers: ['name', 'birthdate', 'gender'])

source: http://ruby-doc.org/stdlib-2.2.0/libdoc/csv/rdoc/CSV.html#method-c-new

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.