Skip to content

Instantly share code, notes, and snippets.

View Sylvain's full-sized avatar

Sylvain Gautier Sylvain

View GitHub Profile
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html
format.csv { send_data ExportToCsv.new(@users).call, filename: "users-#{Date.today}.csv" }
end
end
end
class ExportToCsv
attr_reader :records
def initialize(records)
@records = records
end
def call
CSV.generate(headers: true) do |csv|
csv << header
class ExportUsersToCsv
attr_reader :users
def initialize(users)
@users = users
end
def call
CSV.generate(headers: true) do |csv|
csv << header
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html
format.csv { send_data ExportUsersToCsv.new(@users).call, filename: "users-#{Date.today}.csv" }
end
end
end
feature 'Users' do
context 'export to CSV' do
scenario "users can be exported to CSV" do
user1 = FactoryGirl.create(:user)
user2 = FactoryGirl.create(:user)
visit users_path
click_on I18n.t('global.export')
header = page.response_headers['Content-Disposition']
expect(header).to match /^attachment/
expect(header).to match /filename="users-#{Date.today}.csv"$/
class User < ActiveRecord::Base
def self.to_csv
attributes = %w{id first_name last_name email accepts_emailing}
CSV.generate(headers: true) do |csv|
csv << attributes.map{ |attr| human_attribute_name(attr) }
all.each do |user|
csv << attributes.map do |attr|
if columns_hash[attr] &&
class User < ActiveRecord::Base
def self.to_csv
attributes = %w{id first_name last_name email accepts_emailing}
CSV.generate(headers: true) do |csv|
csv << attributes.map{ |attr| human_attribute_name(attr) }
all.each do |user|
csv << attributes.map{ |attr| user.send(attr) }
end
@Sylvain
Sylvain / fr.yml
Created October 20, 2016 09:27
My refactoring process: Export Users To CSV : Step 2
fr:
activerecord:
models:
user: Utilisateur
attributes:
user:
id: "Identifiant"
first_name: "Prénom"
last_name: "Nom"
email: "E-mail"
@Sylvain
Sylvain / orginal_code.ruby
Last active October 20, 2016 09:26
My refactoring process: Export Users To CSV Step 1
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html
format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" }
end
end
end

Keybase proof

I hereby claim:

  • I am sylvain on github.
  • I am sylvain (https://keybase.io/sylvain) on keybase.
  • I have a public key whose fingerprint is 3AD1 9F85 E2CF E53C 62E7 3FEB 3A38 80EC C1A5 50C7

To claim this, I am signing this object: