For some strange reason I need to save a file (normally downloaded directly) in the server. In my case I have a PDF file created with PDFKit that I need to keep.
# app/controllers/reports_controller.rb
def show
@report = Report.find(params[:id])
respond_to do |format|
format.pdf { render :text => PDFKit.new(report_url(@report)).to_pdf }
end
end
If I go to reports/1.pdf I get the report I am expecting but I want to keep it in the server.
Is there a Raily way to save a file in the server from a respond to?
Just a quick note before I get to the actual answer: It looks like you’re passing a fully-qualified URL (
report_url(@report)) toPDFKit.new, which is a waste–it means PDFKit has to make a request to the web server, which in turn needs to go through Rails’ router and so on down the line to fetch the contents of the page. Instead you should just render the page inside your controller withrender_to_stringand pass it toPDFKit.new, since it will accept an HTML string. Keeping that in mind…This is covered in the “Usage” section of PDFKit’s README. You would do something like this: