· 6 years ago · Jun 22, 2019, 10:34 PM
1class User < ApplicationRecord
2 validates :email, uniqueness: true, unless: :gmail?
3 validates :email, :unique_gmail, if: :gmail?
4
5 def unique_gmail
6 username, symbol, domain = email.partition '@'
7 email_without_periods = "#{username.delete('.')}#{symbol}#{domain}"
8 duplicate = self.class.find_by email: email_without_periods
9 errors.add :email, "#{duplicate} has already been taken" if duplicate
10 end
11
12 private
13
14 def gmail?
15 email.ends_with? '@gmail.com'
16 end
17end