This post originated from an RSS feed registered with Ruby Buzz
by Robby Russell.
Original Post: Sending email: Controllers versus Models
Feed Title: Robby on Rails
Feed URL: http://feeds.feedburner.com/RobbyOnRails
Feed Description: Ruby on Rails development, consulting, and hosting from the trenches...
While reviewing some code recently, I came across controller code that resembled the following.
if@customer.saveCustomerMailer.deliver_welcome_message(@customer)flash[:message]="Your account has been successfully created. We've sent you a welcome letter with..."redirect_todashboard_pathelse...end
Fairly typical Rails code. Nothing alarming here, but I wanted to evaluate the call to the mailer in this scenario. When it comes to sending emails from your application, you can choose to do it from the controller as in the example above or in your models. Our team prefers to do this from our model via a callback as we are considering this to be part of our business logic.
Each time a customer is created, we want to send them an email. This can be moved into the model and resembled something like the following..
after_create:send_welcome_message#, other callbacks..def send_welcome_messageCustomerMailer.deliver_welcome_message(self)end
There are a few benefits to doing it this way.
We can test that this is being triggered within our model specs instead of our controller specs. (we prefer to spend more of our time working within models than controllers)
We remove the dependency that all requests must be processed through our controllers.
Example: We may one day create rake tasks that data and want these emails to still be sent out. (We’ve had to do this a few times)
I definitely don’t think doing this via controllers is a bad idea, I just lean towards keeping controllers as dumbed down as possible. This allows us to have less controller code that is focused on passing data to/from models and letting our models do the heavy lifting.