DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simplifying ActionMailer Development In Ruby On Rails

02.02.2006
| 11570 views |
  • submit to reddit
        Sick 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

<em>(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)</em>

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"
)
    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:19pm

I just took a break from working on an app to check my rss feeds: Next on the todo list was a 'contact us' form. Literally, I was going to write this same thing 10 minutes from now. You (and this site) rock.