Created
February 5, 2020 15:13
-
-
Save lloeki/3c93105028b9f2ab072954f482ed8fb1 to your computer and use it in GitHub Desktop.
Render CSV from Rails respond_with
This file contains 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
# Use with render :csv => foo and respond_with @foo if @foo responds to to_csv | |
# see ActionController::Responder#to_format and #api_behavior | |
ActionController::Renderers.add(:csv) do |obj, options| | |
csv = if obj.respond_to?(:to_csv) | |
obj.to_csv(options[:csv_options] || {}) | |
else | |
obj | |
end | |
headers['Content-Disposition'] = if options[:filename].blank? | |
'attachment' | |
else | |
'attachment;'\ | |
" filename=#{options[:filename]}" | |
end | |
self.content_type ||= Mime::CSV | |
csv | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment