Reputation: 7122
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.
Upvotes: 3
Views: 3945
Reputation: 10701
If you find this and want to do this on Rails 3, this gist was a big help:
https://gist.github.com/aliang/1022384
Upvotes: 0
Reputation: 5245
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 ;-)
Upvotes: 3
Reputation: 9341
If you're looking for an elegant solution, perhaps you could implement an ActionFaxer::Base. You'd be able to follow the implementation of ActionMailer::Base but specialize it for faxes. Taking this approach should give you access to render_to_string.
Of note, in this case you wouldn't be adding render_to_string to a model, but instead introducing the concept of a Faxer, which would deal with models.
If you just need arbitrary support for rendering templates within a model you could code directly against erb or another template language implementation.
The nice thing about the Faxer concept is that it could abstract away more then simply rendering to include things like dispatching, queueing and guaranteeing delivery.
If you're successful, maybe when you're done you could turn it into a gem.
Upvotes: 3