Ruby on Rails / ActionMailer
Interceptors are kind of hooks like
before_save hook for our models. They are perfect in a case where you have to edit email message before it’s delivered. Let’s assume that you have staging environment and you want to send all emails to [email protected] email inbox.
I prefer creating new interceptors in app/interceptors directory and using
*_interceptor.rb naming pattern. In our case we will save our class named as
class StagingEmailInterceptor def self.delivering_email(message) message.to = ['[email protected]'] end end
The second step is the interceptor registration. We have to create new initializer in
config/initializers/staging_email_interceptor.rb directory to let
ActionMailer know that we want to use our interceptor:
if Rails.env.staging? ActionMailer::Base.register_interceptor(StagingEmailInterceptor) end
We are ready now to test emails delivery on the staging environment.