summaryrefslogtreecommitdiff
path: root/users/app/models/local_email.rb
blob: d23df71679207f6f962592a586351fbc8105d910 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class LocalEmail < Email

  validate :unique_on_server
  validate :unique_alias_for_user
  validate :differs_from_main_email
  before_validation :add_domain_if_needed
  validates :email,
    :presence => true,
    :format => { :with => /@#{APP_CONFIG[:domain]}\Z/,
      :message => "needs to end in @#{APP_CONFIG[:domain]}"}
  validates :casted_by, :presence => true

  def to_partial_path
    "emails/email"
  end

  protected

  def unique_on_server
    has_email = User.find_by_email_or_alias(email)
    if has_email && has_email != self.base_doc
      errors.add :email, "has already been taken"
    end
  end

  def unique_alias_for_user
    aliases = self.casted_by.email_aliases
    if aliases.select{|a|a.email == self.email}.count > 1
      errors.add :email, "is already your alias"
    end
  end

  def differs_from_main_email
    # If this has not changed but the email let's mark the email invalid instead.
    return if self.persisted?
    user = self.casted_by
    if user.email == self.email
      errors.add :email, "may not be the same as your email address"
    end
  end

  def add_domain_if_needed
    if email.blank?
      errors.add :email, "may not be empty."
    end
    self.email += "@" + APP_CONFIG[:domain] unless self.email.include?("@")
  end

end