Created
October 16, 2012 23:12
-
-
Save efatsi/3902669 to your computer and use it in GitHub Desktop.
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 Email | |
def initialize(address) | |
@address = address | |
end | |
def valid? | |
@address.match(email_regex) | |
end | |
def to_s | |
@address | |
end | |
private | |
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 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 EmailParser | |
def initialize(email_addresses) | |
@email_addresses = email_addresses | |
end | |
def parsed | |
@email_addresses.split(/[,\n]/).map {|email| | |
email.blank? ? nil : Email.new(email.gsub(/\s/, "")) | |
}.compact | |
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 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 parsed_emails | |
EmailParser.new(email_addresses).parsed | |
end | |
def email_addresses_are_valid | |
if email_addresses.present? | |
erroneous_emails = parsed_emails.select { |email| | |
!email.valid? | |
} | |
errors.add(:email_addresses, error_message(erroneous_emails)) if erroneous_emails.any? | |
end | |
end | |
def error_message(erroneous_emails) | |
emails = erroneous_emails.join(", ") | |
details = erroneous_emails.length == 1 ? "is not a valid email address" : "are not valid email addresses" | |
"#{emails} #{details}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment