Allow sorting of User/Domain for testing.
[mailshears.git] / lib / common / user.rb
1 require 'common/domain'
2 require 'common/errors'
3
4 class User
5 # A class representing a syntactically valid user; that is, an email
6 # address. Once constructed, you can be sure that it's valid.
7
8 @localpart = nil
9 @domain = nil
10
11 def domain()
12 return @domain
13 end
14
15 def domainpart()
16 return @domain.to_s()
17 end
18
19 def initialize(username)
20 # Initialize this user object, but throw an error if either the
21 # localpart or domainpart are invalid. The one argument is an
22 # email address string.
23 if not username.is_a?(String)
24 msg = 'username must be a String '
25 msg += "but a #{username.class.to_s()} was given"
26 raise InvalidUserError.new(msg)
27 end
28
29 parts = username.split('@')
30
31 if parts.length() < 2 then
32 msg = "the username #{username} does not contain an '@' symbol"
33 raise InvalidUserError.new(msg)
34 end
35
36 localpart = parts[0]
37
38 if localpart.length() > 64 then
39 msg = "the local part of #{username} cannot have more than 64 characters"
40 raise InvalidUserError(msg)
41 end
42
43 if localpart.empty? then
44 msg = "the local part of #{username} cannot be empty"
45 raise InvalidUserError.new(msg)
46 end
47
48 @localpart = localpart
49 @domain = Domain.new(parts[1])
50 end
51
52 def localpart()
53 return @localpart
54 end
55
56 def to_s()
57 return @localpart + '@' + @domain.to_s()
58 end
59
60 def ==(other)
61 return self.to_s() == other.to_s()
62 end
63
64 def <=>(other)
65 return self.to_s() <=> other.to_s()
66 end
67 end