Module: HasManyEmails::InstanceMethods

Defined in:
lib/has_many_emails/instance_methods.rb

Instance Method Summary collapse

Instance Method Details

#add_email(value) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/has_many_emails/instance_methods.rb', line 60

def add_email( value )
  value = value.email if value.is_a? HasManyEmails::EmailAddress
  value.downcase!
  return nil if value.blank? || has_email?( value )

  h = { :email=>value }

  if new_record?
    email_addresses.build(:email=>value)
  else
    email_addresses.create(:email=>value)
    email_addresses.reload 
  end
  value
end

#email=(value) ⇒ Object

alias_method :email?, :has_email?



28
29
30
# File 'lib/has_many_emails/instance_methods.rb', line 28

def email=( value )
  super reset_email( value )
end

#emailsObject



50
51
52
# File 'lib/has_many_emails/instance_methods.rb', line 50

def emails
  email_addresses.map(&:email)
end

#find_email_address(value) ⇒ Object



76
77
78
79
80
81
82
83
84
85
# File 'lib/has_many_emails/instance_methods.rb', line 76

def find_email_address( value )
  value.downcase!
  if new_record?
    email_addresses.each { |ea|
      return ea if ea.email==value
    }
  else
    email_addresses.find_by_email value
  end
end

#has_email?(value) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/has_many_emails/instance_methods.rb', line 22

def has_email?( value )
  emails.include?( value.downcase )
end

#remove_email(value) ⇒ Object



54
55
56
57
58
# File 'lib/has_many_emails/instance_methods.rb', line 54

def remove_email( value )
  value.downcase!
  email_address = find_email_address( value ) and email_addresses.delete( email_address )
  email = nil if value==email
end

#reset_email(value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/has_many_emails/instance_methods.rb', line 32

def reset_email( value )
  if value.blank?
    remove_email email if email?
  elsif email? && email_address = find_email_address( email )
    value.downcase!
    return value if value==email
    if new_email_address = find_email_address( value )
      email_addresses.delete( email_address )
    else
      email_address.update_attribute( :email, value ) 
    end
  else
    value.downcase!
    add_email value
  end
  value
end

#validate_email_addressesObject

def emails_uniqueness

# TODO Нормальный перевод
errors.add( :email, "Пользователь с таким емайлом уже зарегистрирован" ) if
  EmailAddress.find_by_email( email )

end



12
13
14
15
16
17
18
19
20
# File 'lib/has_many_emails/instance_methods.rb', line 12

def validate_email_addresses
  email_addresses.each do |email_address|
    if !email_address.valid? && email_address.errors.has_key?(:email)
      email_address.errors[:email].each do |msg|
        errors.add( :email, msg )
      end
    end
  end
end