Rails: Render in a model
June 19, 2008OK, this is really out there. Yes, the real answer is, “Don’t do it.”
Are you sure you aren’t going to be sad when the content of your database doesn’t change to keep up with your refactoring? Have you sufficiently explored other options and questioned the wisdom of what you are trying to do? Are you being asked to just to it anyway?
I found two approaches at http://davetroy.blogspot.com/2008/02/actsasrenderer-brings-output-to-models.html and http://blog.choonkeat.com/weblog/2006/08/rails-calling-r.html. I only tried the second of these, which didn’t like my use of polymorphic URLs and named routes in the template. I didn’t find the first approach before I had an interesting realization: if functional tests can do it then why can’t models?
def render_as_test(render_options, vars = {}) controller = ApplicationController.new class << controller def set_instance_variables_and_render(render_options, vars) vars.keys.each do |k| instance_variable_set "@#{k}", vars[k] end render render_options end end require 'action_controller/test_process' request = ActionController::TestRequest.new response = ActionController::TestResponse.new controller.process(request, response, :set_instance_variables_and_render, render_options, vars).body end
Now all my URLs generate. Use it responsibly. In fact, don’t use it at all. I am definitely not interested in pluginizing.
Thanks, I had looked at those other examples and also had problems with URL generation. Extremely clever your approach! 🙂
by Vidal Graupera July 9, 2008 at 3:04 pmvery clever, this is the first example that really works 🙂
by Pablo August 22, 2013 at 5:27 am[…] https://mattwindsurfs.wordpress.com/2008/06/19/rails-render-in-a-model/ […]
by Rails, How to render a view/partial in a model - PhotoLens February 28, 2022 at 12:36 pm[…] https://mattwindsurfs.wordpress.com/2008/06/19/rails-render-in-a-model/ […]
by Rails, How to render a view/partial in a model – Code D3 August 21, 2022 at 1:57 pm[…] https://mattwindsurfs.wordpress.com/2008/06/19/rails-render-in-a-model/ […]
by Rails, How to render a view/partial in a model – Row Coding May 19, 2023 at 1:49 pm