I've recently upgraded to ahoy_email version 2.0.3 from 1.1.1 and i've been refactoring my code to work with the latest version but i'm having a bit of an issue with a piece of functionality i used to have. The problem is the following:
I want to be able to disable tracking for some of the mails that get sent.
With the changes made to ahoy_email in version 2.0.0, all of the class methods that set the ahoy_settings perform add a before_action which merges the options set from on of the three methods, i.e. track_clicks
, has_history
and utm_params
, so since the options only get merged in a before_action i can't do something like the following:
class DigestMailer < ActionMailer::Base
has_history user: -> { @recipient }, extra: -> { {digest_message_id: @digest_message.id} }
track_clicks campaign: "digest"
def digest(digest_message, user, **options)
@recipient = user
@digest_message = digest_message
self.class.has_history options
....
end
end
DigestMailer.digest(DigestMessage.first, User.first, click: false, message: false).deliver_now
The options i've set in the digest action wouldn't actually get merged, since they are supposed to get merged before calling the digest
action
What i could do tho, is the following:
class DigestMailer < ActionMailer::Base
has_history user: -> { @recipient }, extra: -> { {digest_message_id: @digest_message.id} }
track_clicks campaign: "digest"
def digest digest_message, user, **options
@recipient = user
@digest_message = digest_message
self.ahoy_options = AhoyEmail.default_options.merge(options)
end
end
DigestMailer.digest(DigestMessage.first, User.first, click: false, message: false).deliver_now
This works, because i'm overriding the ahoy_options
attribute after the before_action
callback gets called and before the after_action
callbacks get called and it works.
So my question is: Is this the right way to go about this?
Because this commit, from 3 years ago, clearly says:
Keep old method of disabling tracking
But it's nowhere to be found in the documentation.
To anyone who runs into the same problem, i've found the solution and it consists of two things:
Using a parametrized mailer and using the :if
option of the track_clicks
, has_history
and utm_params
. The code can be rewritten as the following:
class DigestMailer < ActionMailer::Base
has_history(
user: -> { params[:recipient] },
extra: -> { {digest_message_id: params[:digest_message].id} },
if: -> { params[:options].try(:fetch, :message) != false }
)
track_clicks(
campaign: "digest",
if: -> { params[:options].try(:fetch, :track_clicks) != false }
)
def digest
recipient = params[:recipient]
digest_message = params[:digest_message]
Rails.logger.info "Sending digest to #{recipient} with email #{recipient.data.email}"
internal_send_digest_message(digest_message.title)
end
end
DigestMailer.with(digest_message:DigestMessage.first, recipient: User.first, options: {track_clicks: false, message: false}).deliver_now
And it will work as expected.