-
-
Save reagent/3903762 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 address | |
@address.strip | |
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 EmailCollection | |
include Enumerable | |
delegate :each, :to => :emails | |
def initialize(email_addresses) | |
@email_addresses = email_addresses | |
end | |
def emails | |
@emails ||= emails_from_source.map {|e| Email.new(e) } | |
end | |
def valid | |
emails.select(&:valid?) | |
end | |
def invalid | |
emails - valid | |
end | |
def valid? | |
invalid_emails.any? | |
end | |
private | |
def emails_from_source | |
@email_addresses.split(/[,\n]+/).reject(&:blank?) | |
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 email_addresses | |
@email_addresses ||= EmailCollection.new(email_addresses) | |
end | |
def email_addresses_are_valid | |
if !email_addresses.valid? | |
message = email_addresses.invalid.join(', ') + ' ' | |
message << email_addresses.invalid.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
This code is incorrect, but the sentiment is there.