Reputation: 7011
I'm exporting a bunch of records to a CSV like so:
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 read like 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 within CSV.generate
?
Update Lookup hash.
def lookup
{
full_name: 'Full Name', first_name: 'First Name', last_name: 'Last Name', created_at: 'Generation Date', status: 'Status'
}
end
Upvotes: 5
Views: 4739
Reputation: 4857
Calling titalize on the attributes array should help you achieve what your 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
Upvotes: 3