-
-
Save samnang/980151587855c151d639 to your computer and use it in GitHub Desktop.
This file contains 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 SignupInviter | |
include ActiveModel::Model | |
EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/ | |
attr_accessor :recipients, :sender | |
validates :sender, :recipients, presence: true | |
validate :ensure_recipient_emails | |
def deliver | |
return false unless valid? | |
if recipients_without_users.any? | |
create_invitations | |
send_invitations | |
end | |
true | |
end | |
private | |
def ensure_recipient_emails | |
if has_any_invalid_recipient_email? | |
errors.add(:recipients, "have invalid email format") | |
end | |
end | |
def create_invitations | |
recipients_without_users.each do |recipient_email| | |
Invitation.create!(sender: sender, recipient_email: recipient_email) | |
end | |
end | |
def send_invitations | |
SendSignupInvitationsWorker.perform_async(sender.id, recipients_without_users) | |
end | |
def has_any_invalid_recipient_email? | |
recipients && recipients.any? { |email| email !~ EMAIL_REGEX } | |
end | |
def recipients_without_users | |
@recipients_without_users ||= begin | |
emails = User.where(email: recipients).pluck(:email) | |
recipients - emails | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment