Skip to content

Instantly share code, notes, and snippets.

@miharekar
Last active February 24, 2023 14:33
Show Gist options
  • Save miharekar/425a88e24ec14a690b6bcf13816f7004 to your computer and use it in GitHub Desktop.
Save miharekar/425a88e24ec14a690b6bcf13816f7004 to your computer and use it in GitHub Desktop.
Prevent email sending in Rails.md

#rails #actionmailer #callbacks

Callbacks for mailers are implemented using AbstractController::Callbacks.

This has a terminator lambda: https://github.com/rails/rails/blob/6af9cba73db6296ab9aec7dbeae1e193ea69f09f/actionpack/lib/abstract_controller/callbacks.rb#L34

AbstractController::Base defines performed? as: return response_body https://github.com/rails/rails/blob/6af9cba73db6296ab9aec7dbeae1e193ea69f09f/actionpack/lib/abstract_controller/base.rb#L188

So - as soon as we set any response body, no other callbacks or actions will occur.

Simple implementation:

class ApplicationMailer < ActionMailer::Base
  before_action :check_subscription

  private

  def check_subscription
    return unless params[:user].is_a?(User)

    prefix = self.class.name.sub(/Mailer$/, "").underscore.to_sym
    return unless User::ALL_EMAIL_SUBSCRIPTIONS.fetch(prefix, []).include?(action_name.to_sym)

    subscription = "#{prefix}_#{action_name}"
    self.response_body = :do_not_deliver unless params[:user].subscribed_to?(subscription)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment