require 'common/domain' require 'common/errors' # A class representing a syntactically valid user; that is, an email # address. Once constructed, you can be sure that it's valid. # class User # @localpart is a String containing the "user" part of "user@domain". @localpart = nil # @domain contains a {Domain} object representing the domain part of # "user@domain". @domain = nil # Obtain the {Domain} object corresponding to this User. # # @return [Domain] the domain corresponding to this User. # def domain() return @domain end # Obtain the domain part of this User object as a string. # # @return [String] a String representation of this User's domain. # def domainpart() return @domain.to_s() end # Initialize this User object. If either of the local/domain parts # is invalid, then either an {InvalidUserError} or an {InvalidDomainError} # will be raised containing the reason why that part is invalid. # # @param username [String] an email address from which to construct # this User. # def initialize(username) if not username.is_a?(String) msg = 'username must be a String ' msg += "but a #{username.class.to_s()} was given" raise InvalidUserError.new(msg) end parts = username.split('@') if parts.length() < 2 then msg = "the username #{username} does not contain an '@' symbol" raise InvalidUserError.new(msg) end localpart = parts[0] if localpart.length() > 64 then msg = "the local part of #{username} cannot have more than 64 characters" raise InvalidUserError(msg) end if localpart.empty? then msg = "the local part of #{username} cannot be empty" raise InvalidUserError.new(msg) end @localpart = localpart @domain = Domain.new(parts[1]) end # Obtain the "user" part of this User object as a String. # # @return [String] the "user" part of this User's "user@domain" # address. # def localpart() return @localpart end # Convert this User to an email address string. # # @return [String] an email address String constructed from this # user's local and domain parts. # def to_s() return @localpart + '@' + @domain.to_s() end # Check if this User is equal to some other User. The comparison # is based on their String representations. # # @param other [User] the User object to compare me to. # # @return [Boolean] If *self* and *other* have equal String # representations, then true is returned. Otherwise, false is # returned. # def ==(other) return self.to_s() == other.to_s() end # Compare two User objects for sorting purposes. The comparison is # is based on their String representations. # # @param other [User] the User object to compare me to. # # @return [0,1,-1] a trinary indicator of how *self* relates to *other*, # obtained by performing the same comparison on the String # representations of *self* and *other*. # def <=>(other) return self.to_s() <=> other.to_s() end end