We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

ryanprel on 02/08/07


Tagged

rails ActionMailer


Versions (?)


Who likes this?

6 people have marked this snippet as a favorite

adam_dc
maxkks
bordalix
edwinjanmoss
vali29
tkmr


ActionMailer


Published in: Ruby 


Sick of writing almost the same thing over and over in your ActionMailer classes? Skip all that, and use something like this.

(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:

  1. class Mailer < ActionMailer::Base
  2.  
  3. helper ActionView::Helpers::UrlHelper
  4.  
  5. def generic_mailer(options)
  6. @recipients = options[:recipients] || "me@privacy.net"
  7. @from = options[:from] || "me@privacy.net"
  8. @cc = options[:cc] || ""
  9. @bcc = options[:bcc] || ""
  10. @subject = options[:subject] || ""
  11. @body = options[:body] || {}
  12. @headers = options[:headers] || {}
  13. @charset = options[:charset] || "utf-8"
  14. end
  15.  
  16. # Create placeholders for whichever e-mails you need to deal with.
  17. # Override mail elements where necessary
  18.  
  19. def contact_us(options)
  20. self.generic_mailer(options)
  21. end
  22.  
  23. ...
  24.  
  25. end
  26.  
  27.  
  28.  
  29. Mailer.deliver_contact_us(
  30. :recipients => "x@x.com",
  31. :body => {
  32. :name => params[:name],
  33. :phone => params[:phone],
  34. :email => params[:email],
  35. :message => params[:message]
  36. },
  37. :from => "y@y.com"
  38. )

Report this snippet 

You need to login to post a comment.