Class: UsernameSuggester::Suggester

Inherits:
Object
  • Object
show all
Defined in:
lib/username_suggester/suggester.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(first_name, last_name) ⇒ Suggester

A Suggester class to suggest user_names

Parameters

  • :first_name - Required.

  • :last_name - Required.

  • :options - See UsernameSuggester::SuggestionsFor

Raises:



14
15
16
17
18
19
# File 'lib/username_suggester/suggester.rb', line 14

def initialize(first_name, last_name)
  raise Error, "first_name or last_name has not been specified" if first_name.nil? || last_name.nil?

  @first_name = first_name.downcase.gsub(/[^\w]/, '')
  @last_name  = last_name.downcase.gsub(/[^\w]/, '')
end

Instance Attribute Details

#first_nameObject (readonly)

Returns the value of attribute first_name.



4
5
6
# File 'lib/username_suggester/suggester.rb', line 4

def first_name
  @first_name
end

#last_nameObject (readonly)

Returns the value of attribute last_name.



4
5
6
# File 'lib/username_suggester/suggester.rb', line 4

def last_name
  @last_name
end

Instance Method Details

#name_combinationsObject

Generates the combinations without the knowledge of what names are available



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/username_suggester/suggester.rb', line 22

def name_combinations
  @name_combinations ||= [
    "#{first_name}",
    "#{last_name}",
    "#{first_name[0]}#{last_name}",
    "#{first_name}#{last_name[0]}",
    "#{first_name}#{last_name}",
    "#{last_name[0]}#{first_name}",
    "#{last_name}#{first_name[0]}",
    "#{last_name}#{first_name}"
  ].uniq.reject { |s| s.blank? }
end

#suggest(options) ⇒ Object

Generates suggestions and making sure they are not in unavailable_suggestions



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/username_suggester/suggester.rb', line 36

def suggest(options)
  candidates_to_exclude = options[:exclude]
  validation_block      = options[:validate]
  number_of_suggestions = options[:num_suggestions]

  results    = []
  candidates = name_combinations.clone
  while results.size < number_of_suggestions && !candidates.blank?
    candidate = candidates.shift
    if validation_block.try(:call, candidate)
      # Don't add the candidate to result
    elsif candidates_to_exclude.include? candidate
      candidates << find_extended_candidate(candidate, candidates_to_exclude)
    else
      results << candidate
    end
  end

  results
end