Skip to content

Instantly share code, notes, and snippets.

@stefanosc
Forked from jonmagic/email.rb
Created March 15, 2016 23:07
Show Gist options
  • Save stefanosc/1c8ebf389a183d116cba to your computer and use it in GitHub Desktop.
Save stefanosc/1c8ebf389a183d116cba to your computer and use it in GitHub Desktop.

Revisions

  1. @jonmagic jonmagic revised this gist Mar 13, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion email.rb
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    class Email < ActiveRecord::Base

    # Nope, it's not RFC compliant. Fuck that regex.
    # Nope, it's not RFC compliant. F*** that regex.
    # http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
    EmailRegex = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i.freeze

  2. @jonmagic jonmagic created this gist Mar 13, 2014.
    51 changes: 51 additions & 0 deletions email.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    class Email < ActiveRecord::Base

    # Nope, it's not RFC compliant. Fuck that regex.
    # http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
    EmailRegex = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i.freeze

    before_validation :strip_spaces

    # Public: The email address.
    # column :address
    # Returns a String.
    validates :address,
    :presence => true,
    :length => { :in => 3..254 },
    :format => { :with => EmailRegex, :message => "does not look like an email address" },
    :uniqueness => { :case_sensitive => false, :message => "is taken" }

    # Public: User email address belongs to.
    # column :user_id
    # Returns a User.
    validates :user_id, :presence => true
    belongs_to :user

    # Public: Email address validation as a service.
    #
    # Returns a boolean
    def self.valid_email_address?(email)
    EmailRegex.match(email)
    end

    # Public: Is this a primary email address?
    # column :primary
    # Returns a TrueClass or FalseClass.

    # TODO: Validate that only one Email#address per User is the primary.

    # Public: Set this email as the primary email. Sets primary to false for any
    # other emails for this User.
    def set_primary
    self.class.transaction do
    self.class.where(:user_id => user_id, :primary => true).update_all(:primary => false)
    self.primary = true
    save
    end
    end

    # Internal: Strip all space from the email.
    def strip_spaces
    self.address = address.strip
    end
    end