Skip to content

Instantly share code, notes, and snippets.

@lloeki
Created February 5, 2020 15:13
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 lloeki/3c93105028b9f2ab072954f482ed8fb1 to your computer and use it in GitHub Desktop.
Save lloeki/3c93105028b9f2ab072954f482ed8fb1 to your computer and use it in GitHub Desktop.
Render CSV from Rails respond_with
# 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