user464180
user464180

Reputation: 1359

Concatenate array and string for CSV

I'm attempting to concatenate a string to an array value. Since the URL/domain is the same, I simply store the users email prefix and append the url/domain. I need to export the full email address out to CSV:

 CSV.generate(options) do |csv|
    columns = %w(name, email_address) 
    url = "@example.com"   
    all.each do |location|
      csv << location.attributes.values_at(*columns) + [url]     
    end
  end

Currently the resulting output is:

Joe, user1, @example.com
Bob, user2, @example.com

What I need is:

Joe, [email protected]
Bob, [email protected]

How can I achieve the above?

Upvotes: 0

Views: 782

Answers (2)

tihom
tihom

Reputation: 8003

Try this:

CSV.generate(options) do |csv|
  columns = %w(name, email_address) 
  url = "@example.com"   
  all.each do |location|
    row = location.attributes.values_at(*columns)
    row[-1] = row[-1] + url
    csv << row
  end
end

Currently the array written to CSV is ['Joe', 'user1'] + ['@example.com'], so instead of adding url to the attributes array I am adding it to the last attribute.

Upvotes: 0

SHS
SHS

Reputation: 7744

location is a model object, right?

CSV.generate(options) do |csv|
  domain = "example.com"

  all.each do |location|    
    csv << [location.name, "#{location.email_address}@#{domain}"]
  end
end

Update:

IMO that's cleaner as well. But if you want to keep your version, then I suggest you create a full_email_address method in your Location model which returns something like [email protected].

Then, you can vary the columns data later on and easily modify your CSV output. Like so:

class Location << ActiveRecord::Base
  def full_email_address
    return "" if self.email_address.blank?

    domain = "example.com" # or save this as a constant in the class
    "#{self.email_address}@#{domain}"
  end
end

CSV.generate(options) do |csv|
  columns = %w{name full_email_address} # add other methods or attributes here

  all.each do |location|
    csv << columns.map{ |moa| location.public_send(moa) }
  end
end

Upvotes: 1

Related Questions