Skip to content

Instantly share code, notes, and snippets.

@samnang
Created June 1, 2014 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samnang/980151587855c151d639 to your computer and use it in GitHub Desktop.
Save samnang/980151587855c151d639 to your computer and use it in GitHub Desktop.
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