Rails interceptors

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.

Interceptor creation

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

class StagingEmailInterceptor
  def self.delivering_email(message)
    message.to = ['[email protected]']

Interceptor registration

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?

We are ready now to test emails delivery on the staging environment.