Module: UsernameSuggester::SuggestionsFor::ClassMethods

Defined in:
lib/username_suggester/suggestions_for.rb

Instance Method Summary collapse

Instance Method Details

#suggestions_for(attribute = :username, option_hash = {}) ⇒ Object

Creates method to generate suggestions for an username attributes. Example:

suggestions_for :username, :num_suggestions => 5, 
  :first_name_attribute => :first, :last_name_attribute => last

will creates a “username_suggestions” method which generates suggestions of usernames based on first name and last name

Available options are:

:attribute

The name of the attribute for storing username. Default is :username

:first_name_attribute

The attribute which stores the first name. Default is :first_name

:last_name_attribute

The attribute which stores the last name. Default is :last_name

:num_suggestions

Maximum suggestions generated. Default is 10

:validate: An Proc object which takes in an username and return true if this is an validate username :exclude: An array of strings that should not be suggested



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/username_suggester/suggestions_for.rb', line 24

def suggestions_for(attribute = :username, option_hash = {})
  options = {
    :first_name_attribute => :first_name,
    :last_name_attribute  => :last_name,
    :num_suggestions      => 5,
    :exclude              => []
  }.merge(option_hash)
  
  define_method "#{attribute}_suggestions" do
    suggester = Suggester.new(send(options[:first_name_attribute]), send(options[:last_name_attribute]))
    suggestions_to_search = suggester.name_combinations.map { |s| "#{s}%" }

    t = self.class.arel_table
    unavailable_choices = self.class.find_by_sql(t.project(t[attribute])
                            .where(t[attribute].matches_any(suggestions_to_search).and(t[:id].not_eq(self.id))).to_sql)
                              .map(&attribute).map(&:downcase).uniq

    options[:exclude] += unavailable_choices
    suggester.suggest(options)
  end
end