I would love to call a controller action from within a model. Yes, MVC. Thanks.
So, why would i like to call a controller action and fetch the response?
Because my controller knows how to render the file I would like to cache. Why should I duplicate code to collect all data needed by my view?
Setup:
- InvoicesController responds_to :html, :pdf
- Invoice uses state_machine (:new -> :open -> paid)
What I “need” within the state transition from :new to :open
- generate /invoices/:id.pdf
- cache the PDF as Invoice#file for later use in delayed_job or simliar
What interface i would love to use elsewhere?
@invoice.build_pdf
Any suggestions?
Update:
I would like to cache the PDF as model attachement for later use (delayed_job mailing, etc)
It may be better to take the code you’re using in your controller to render the PDF data, and create a module or class in your
libdirectory let’s saylib/pdf.rbthen use that code in both your controller and your model.Update: You can cache the PDF itself on the filesystem as a file with a timestamp as it’s name or something like that that is uniquely identifiable. Then add a
fileorinvoiceattribute to the model to store the location in the database for later use.Update: You can use the block form of
respond_tolike so:Update: It seems that
ActionDispatch::Integration::Sessionis a class for creating and interface for integration testing. But I think you could exploit it for your purposes.You should be able to use it like this:
Another way would be to grab the content by using
curli.e.curl http://localhost:3000/invoices/1.pdfand store the output.