Simplifying ActionMailer Development In Ruby On Rails
Join the DZone community and get the full member experience.
Join For FreeSick of writing almost the same thing over and over in your ActionMailer classes? Skip all that, and use something like this.
class Mailer < ActionMailer::Base
helper ActionView::Helpers::UrlHelper
def generic_mailer(options)
@recipients = options[:recipients] || "me@privacy.net"
@from = options[:from] || "me@privacy.net"
@cc = options[:cc] || ""
@bcc = options[:bcc] || ""
@subject = options[:subject] || ""
@body = options[:body] || {}
@headers = options[:headers] || {}
@charset = options[:charset] || "utf-8"
end
# Create placeholders for whichever e-mails you need to deal with.
# Override mail elements where necessary
def contact_us(options)
self.generic_mailer(options)
end
...
end
(If you have a configuration loaded into a constant, you could just replace the defaults above and use your app's defaults to make it all cleaner, of course)
And then from your controller you can do stuff like this:
Mailer.deliver_contact_us(
:recipients => "x@x.com",
:body => {
:name => params[:name],
:phone => params[:phone],
:email => params[:email],
:message => params[:message]
},
:from => "y@y.com"
)
Opinions expressed by DZone contributors are their own.
Comments