288 | Chapter 9: Incorporating and Extending Rails
Mailer classes and their email templates are defined just as they are in Rails:
class Mailer < ActionMailer::Base
def quota_exceeded_notification(user)
from "System Administrator <[email protected]>"
recipients name_and_email(user)
subject "Your account is over the quota"
body {:user => user}
end
private
# "John Smith <[email protected]>"
def name_and_email(user)
"#{user.full_name} <#{user.email}>"
end
end
The template follows the usual pattern, and is located under our template root, in
views/mailer/quota_exceeded_notification.erb:
Dear <%= @user.name %>,
Your account is over its storage quota. You are currently using
<%= human_size(user.storage_used) %>, and your limit is
<%= human_size(user.account.quota) %>.
Please reduce your usage within 5 days or we will reduce it for you.
Regards,
The Management
Now, this Mailer class can be used just as if it were inside a Rails application. We’ll
look at one possible application for this next.
Custom Rake tasks
Rake is best known in Rails for its purposes in testing. Rake is used to kick off Rails
tests, but also to perform administrative functionality (database maintenance and
migrations, managing temporary files and sessions, and the like). We can easily
extend Rake to handle any application-specific maintenance we need to do; in this
case, to find users who are over their quota and send them a nasty email. (For sim-
plicity, we will abstract away some of the details of finding those users.)
Here is a customRakefile that provides the email functionality:
require 'rake'
# Mailer setup commands from above
require 'mailer_config'
# ActiveRecord setup, not shown
require 'ar_users'