For my Rails app, we developed an half home-brewed email system. We created a model called Email which then gets added to a queue to be sent (using a web service).
To create templates, we’ve been just mashing strings together in the model, ie:
Email < ActiveRecord::Base
def self.stock_message(recipient)
email = Email.create do |e|
e.recipient = recipient
e.message = String.new
e.message << "first line <br />"
e.message << "second line <br />"
end
end
end
#to send:
e = Email.stock_message "foo@bar.baz"
This clearly violates MVC and really becomes a problem when I want to format strings using helper methods. How can I properly separate the view code from the model?
I think you can use
render_to_stringmethod, but as it is not availble in model, you need to call it from controller:If you need to pass some variables to render method, then just add
:locals => {:var1 => value, :var2 => value2}.In this example you should store views for emails in
app/views/emails/directory.However, as @David said, why not use mailer provided by Rails? It would be better solution.