Automatically unsubscribe from emails in Rails.
Add this line to your application's Gemfile:
gem 'unsubscribe'And then execute:
$ bundleOr install it yourself as:
$ gem install unsubscribeThen run the installation commands:
rails g unsubscribe:install
rails unsubscribe:install:migrations
rails db:migrate- Add
include Unsubscribe::Ownerto aModel. TheModelmust have anemailcolumn.
class User < ApplicationRecord
include Unsubscribe::Owner
endUser.first.mailer_subscriptions
# => #<ActiveRecord::Associations::CollectionProxy [#<Unsubscribe::MailerSubscription>, #<Unsubscribe::MailerSubscription>] >
User.first.subscribed_to_mailer? "MarketingMailer"
# => true/false
User.first.to_sgid_for_mailer_subscription
# => #<SignedGlobalID:123 ...>- Add
include Unsubscribe::Mailerto aMailer. - Optionally call
unsubscribe_settingsto set anameanddescription. This will be used in the unsubscribe page. - Set
mail to:to@recipient.email. The@recipientis an instance of whatever Classinclude Unsubscribe::Ownerwas added to.
class MarketingMailer < ApplicationMailer
include Unsubscribe::Mailer
unsubscribe_settings name: "Marketing Emails", description: "Updates on promotions and sales."
def promotion
mail to: @recipient.email
end
end- Call the
Mailerwith arecipientparameter.
MarketingMailer.with(
recipient: User.first
).promotion.deliver_nowUnsubscribe::MailerSubscription.first.action
# => "Unsubscribe from"/"Subscribe to"
Unsubscribe::MailerSubscription.first.call_to_action
# => "Unsubscribe from Marketing Emails"/"Subscribe to Marketing Emails"
Unsubscribe::MailerSubscription.first.description
# => "Updates on promotions and sales."
Unsubscribe::MailerSubscription.first.name
# => "Marketing Emails"- Add the
@unsubscribe_urllink to theMailer.
<%= link_to "Unsubscribe", @unsubscribe_url %>Run rails g unsubscribe:views if you want to modify the existing templates.
The language used for Unsubscribe::MailerSubscription#action can be translated.
# config/locales/en.yml
en:
unsubscribe:
action:
subscribe: "Subscribe to"
unsubscribe: "Unsubscribe from"If you'd like to open a PR please make sure the following things pass:
bin/rails test
bundle exec standardrbThe gem is available as open source under the terms of the MIT License.
