Created
July 21, 2014 00:43
-
-
Save joshmcarthur/6a02f7146806d2b06537 to your computer and use it in GitHub Desktop.
Support rendering CSV content directly as an attachment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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