Skip to content

Instantly share code, notes, and snippets.

@reagent

reagent/email.rb

Forked from efatsi/email.rb
Created Oct 17, 2012
Embed
What would you like to do?
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
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
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
@reagent

This comment has been minimized.

Copy link
Owner Author

@reagent reagent commented Oct 17, 2012

This code is incorrect, but the sentiment is there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.