Rails: CSV.generate and renaming headers

I am exporting a bunch of records to CSV, for example:

def self.to_csv
  attributes = %w(full_name first_name last_name created_at status)

  CSV.generate(headers: true) do |csv|
    csv << attributes
    all.each do |lead|
      csv << attributes.map { |attr| lead.send(attr) }
    end
  end
end

      

But I need the headers to be read as Full Name

not full_name

. I need a hash to match the names, which is fine, but how do I write the new header names to the CSV file in CSV.generate

?

Update search hash.

def lookup
  {
    full_name: 'Full Name', first_name: 'First Name', last_name: 'Last Name', created_at: 'Generation Date', status: 'Status'
  }
end

      

+3


source to share


1 answer


Calling titalize on an array of attributes should help you achieve what you were aiming for.



def self.to_csv
  CSV.generate(headers: true) do |csv|
    csv << lookup.values
    all.each do |lead|
      csv << lookup.keys.map { |attr| lead.send(attr) }
    end
  end
end

      

+1


source







All Articles