ActionMailer::Preview callbacks?

61 Views Asked by At

ActionMailer::Base provides call backs like ActionController::Base does which allows for common code to be called before a mailer function/action. It seems this is not supported for ActionMailer::Preview classes but could be useful. Is there a module I can include that would give me this functionality so I can call something like:

class MailerPreview < ActionMailer::Preview
  include SomeCallBackModule

  before_action :create_records

  def mailer_a
    # Don't need this anymore because create_records gets called
    # @user = FactoryBot.create(:some_factory)
    # @widget = FactoryBot.create(:another_factory, user: @user)
    Mailer.mailer_a(@user, @widget)
  end

  def mailer_b
    # Don't need this anymore because create_records gets called
    # @user = FactoryBot.create(:some_factory)
    # @widget = FactoryBot.create(:another_factory, user: @user)
    Mailer.mailer_b(@user, @widget)
  def

  private

  def create_records
    @user = FactoryBot.create(:some_factory)
    @widget = FactoryBot.create(:another_factory, user: @user)
  end
end
1

There are 1 best solutions below

3
spickermann On

ActionMailer::Preview indeed doesn't support callbacks out of the box.

In your example, I would suggest calling a simple private method directly instead of with a callback:

class MailerPreview < ActionMailer::Preview
  def mailer_a
    Mailer.mailer_a(user)
  end

  def mailer_b
    Mailer.mailer_b(user)
  def

  private

  def user
    @user ||= User.first
  end
end