0

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?

2
  • csv << [location.name, "#{location.email_address}@example.com"] should work. Commented Dec 19, 2014 at 14:11
  • 1
    Hello, @Stefan. You've been AWOL. Commented Dec 19, 2014 at 15:23

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

row[-1] += url would be better
row[-1] << url would be even better.

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.