Skip to content

Instantly share code, notes, and snippets.

@nerab
Created May 5, 2012 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nerab/2605995 to your computer and use it in GitHub Desktop.
Save nerab/2605995 to your computer and use it in GitHub Desktop.
Produce and consume CSV with Rails
# from http://speakerdeck.com/u/jeg2/p/10-things-you-didnt-know-rails-could-do slide 64
require "csv"
namespace :users do
desc "Import users from a CSV file"
task :import => :environment do
path = ENV.fetch("CSV_FILE") {
File.join(File.dirname(__FILE__), *%w[.. .. db data users.csv])
}
CSV.foreach(path, headers: true, header_converters: :symbol) do |row|
User.create(row.to_hash)
end
end
end
# from http://speakerdeck.com/u/jeg2/p/10-things-you-didnt-know-rails-could-do slide 199
class ArticlesController < ApplicationController
def index
respond_to do |format|
format.html do
@articles = Article.all
end
format.csv do
headers["Content-Disposition"] = %Q{attachment; filename="articles.csv"}
self.response_body = Enumerator.new do |response|
csv = CSV.new(response, row_sep: "\n")
csv << %w[Subject Created Status]
Article.find_each do |article|
csv << [ article.subject,
article.created_at.to_s(:long),
article.status ]
end
end
end
end
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment