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::BaseI 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.class_inheritable_accessor :smtp_settingsend
def self.smtp_settingsHash.new {|h, k|endPreference["smtp.#{k.to_s}"]}
If somebody knows of a better way to do it, feel free to add a comment or a link.
No comments:
Post a Comment