Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render_to_string in a rails model?

How do I render_to_string in a model in rails?

If you say that, "You should never be rendering anything from a model. Any rendering -- at all -- is the responsibility of the controller and view." Hear me out, or suggest a better way you might solve the problem

My model is a mailer. Just not that of emails, faxes.

like image 508
maletor Avatar asked Jan 28 '26 05:01

maletor


1 Answers

Here's working code:

# instance_vars must follow the '@name' convention.
#
def render_template( template_content, options={} )
  local_vars    = options[ :local_vars    ] || {}
  instance_vars = options[ :instance_vars ] || {}

  view = ActionView::Base.new( Rails::Configuration.new.view_path )

  instance_vars.each do | name, value |
    view.instance_variable_set( name, value )
  end

  rendering_options = {
      :inline => template_content,
      :type   => :builder,
      :locals => local_vars
  }

  view.render( rendering_options )
end

Tested on Rails 2.3.14. Note that I didn't find this idea, but just wrapped it in a convenience method.

Of course, don't assume that I advocate views rendering in models because of this ;-)

like image 155
Marcus Avatar answered Jan 30 '26 19:01

Marcus