-
-
Save brianjlandau/3906814 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 EmailCollection | |
include Enumerable | |
delegate :each, :to => :email_addresses | |
def initialize(raw_email_addresses) | |
@raw_email_addresses = raw_email_addresses | |
end | |
def valid_emails | |
select do |email| | |
email.match(email_regex) | |
end | |
end | |
def invalid_emails | |
email_addresses - valid_emails | |
end | |
def valid? | |
invalid_emails.any? | |
end | |
private | |
def email_addresses | |
@raw_email_addresses.split(/[,\n]+/).reject(&:blank?).map(&:strip) | |
end | |
def email_regex | |
email_name_regex = '[A-Z0-9_\.%\+\-\']+' | |
domain_head_regex = '(?:[A-Z0-9\-]+\.)+' | |
domain_tld_regex = '(?:[A-Z]{2,4})' | |
/\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i | |
end | |
end |
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 Invitation < ActiveRecord::Base | |
validate :email_addresses_are_valid | |
def send_invitations | |
parsed_emails.each do |email_address| | |
InvitationMailer.invite(email_address, email_subject, email_body).deliver | |
end | |
end | |
private | |
def email_addresses | |
@email_addresses ||= EmailCollection.new(email_addresses) | |
end | |
def email_addresses_are_valid | |
if !email_addresses.valid? | |
message = email_addresses.invalid_emails.join(', ') + ' ' | |
message << email_addresses.invalid_emails.many? ? "are not valid email addresses" : "is not a valid email address" | |
errors.add(:email_addresses, message) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment