Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created July 21, 2014 00:43
Show Gist options
  • Save joshmcarthur/6a02f7146806d2b06537 to your computer and use it in GitHub Desktop.
Save joshmcarthur/6a02f7146806d2b06537 to your computer and use it in GitHub Desktop.
Support rendering CSV content directly as an attachment
# Save this in config/initializers/csv_renderer.rb
ActionController::Renderers.add :csv do |obj, options|
filename = options[:filename] || 'data.csv'
str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
send_data str,
type: Mime::CSV,
disposition: "attachment",
filename: filename
end
#### USAGE: ####
class WidgestsControoller < ApplicationController
def index
respond_to do |format|
format.csv { render csv: Widget.all, filename: 'widgets.csv' }
format.all { render }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment