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.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With