Created
February 26, 2021 15:36
-
-
Save stympy/3d76041365a61085ddcf01a3461f65f1 to your computer and use it in GitHub Desktop.
Heya broadcasts sample code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Heya::Broadcast < ApplicationRecord | |
FROM_FORMATS = [ | |
/\A\[email protected]\z/, | |
/\A.+ <\[email protected]>\z/ | |
] | |
validates_presence_of :subject, :body | |
validate :valid_from_format | |
def self.create_and_send(subject:, body:, users:, from: nil) | |
broadcast = create!(from: from, subject: subject, body: body) | |
users.find_each do |user| | |
Heya::BroadcastMailer.with(user: user, broadcast: broadcast).build.deliver_later | |
rescue => e | |
warn "Got error for #{user.delivery_email} (#{user.id}):\n #{e}" | |
end | |
end | |
private | |
def valid_from_format | |
return if from.nil? | |
return if FROM_FORMATS.any? { |f| from =~ f } | |
errors.add(:from, "is invalid (must be a honeybadger.io sending domain)") | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Heya::BroadcastMailer < ApplicationMailer | |
DEFAULT_FROM = "The Honeybadger Crew <[email protected]>" | |
default reply_to: "[email protected]" | |
class UserUnsbuscribedError < StandardError | |
end | |
layout "heya/broadcast_mailer" | |
rescue_from UserUnsbuscribedError do |e| | |
Rails.logger.error(e.message) | |
end | |
def build | |
broadcast = params.fetch(:broadcast) | |
user = params.fetch(:user) | |
@body = broadcast.body | |
raise UserUnsbuscribedError.new("Unable to send mail: user unsubscribed") if user.opted_out? | |
mail( | |
from: broadcast.from.presence || DEFAULT_FROM, | |
to: user.email, | |
subject: broadcast.subject | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment