11.15.2007

Loading ActionMailer SMTP settings from the database


Here is a simple way to load your SMTP settings from the database instead of having to call ActionMailer::Base.smtp_settings= in environment.rb, development.rb or production.rb. Using the database to store these setting, while a bit slower, allow one to easily allow an administration to change the configuration without having to restart the Rails application.

The first approach I used was to just override the self.smtp_settings method in my ActionMailer::Base subclass. But that didn't work due to cattr_accessor not working as expected. So I had to also add class_inheritable_accessor :smtp_settings.

So I did the following :
class StuffNotifier < ActionMailer::Base
class_inheritable_accessor :smtp_settings

def self.smtp_settings
Hash.new {|h, k|
Preference["smtp.#{k.to_s}"]
}
end
end
I use Hash.new with a Proc because the stuff the Preference[] method access the database, if I construct an Hash with all the value loaded from the database, then the Hash will be constructed many times as ActionMailer::Base access self.smtp_settings many times when sending an email. Using an empty hash with a default Proc solved my problem. I also prepend "smtp." so it retrieves the "smtp.host" value from my system preference table.

If somebody knows of a better way to do it, feel free to add a comment or a link.




No comments:

AdSense Links