Class: UserAlias

Inherits:
String
  • Object
show all
Defined in:
app/models/user_alias.rb

Overview

The UserAlias is a String that is used for identification during login. It can be chosen by the user and defaults to a combination of first and last name. The alias is unique, i.e. two users can’t have the same alias.

UserAlias.taken?("foo")
alias = user.generate_alias
alias = UserAlias.generate_for(user)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.generate_for(user) ⇒ Object

Generate an alias for a User based on the user’s name.

user.alias = UserAlias.generate_for(user)
user.generate_alias


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/models/user_alias.rb', line 35

def self.generate_for(user)
  raise 'no user given' if not user
  raise 'the given user has no last_name' if not user.last_name.present?
  raise 'the given user has no first_name' if not user.first_name.present?
  
  suggestion = try_to_generate_from_last_name(user)                      # doe
  suggestion ||= try_to_generate_from_first_and_last_name(user)          # j.doe
  suggestion ||= try_to_generate_long_from_first_and_last_name(user)     # john.doe
  suggestion ||= try_to_generate_long_from_name_and_year_of_birth(user)  # john.doe.1986
  
  # If the suggestion is still empty (no successful generation), the empty 
  # alias will raise a validation error and the user will be asked to enter
  # an alias.
  
  return UserAlias.new(suggestion) if suggestion
  return nil
end

.taken?(alias_to_check) ⇒ Boolean

UserAlias.taken? “foo” # => false User.create(alias: “foo”, …) UserAlias.taken? “foo” # => <User …>

Returns:

  • (Boolean)


15
16
17
# File 'app/models/user_alias.rb', line 15

def self.taken?( alias_to_check )
  User.where( :alias => alias_to_check ).try(:first) || false
end

Instance Method Details

#taken?Boolean

Checks if the alias is already taken by a User stored in the database.

user = User.new(alias: "foo")
user.alias.taken?  # => false
user.save
user.alias.taken?  # => <User ...>

Returns:

  • (Boolean)


26
27
28
# File 'app/models/user_alias.rb', line 26

def taken?
  UserAlias.taken? self
end