Module: UsernameSuggester::UsernameSuggestions::ClassMethods
- Defined in:
- lib/username_suggester/suggestions_for.rb
Instance Method Summary collapse
-
#suggestions_for(attribute = :username, options = {}) ⇒ Object
Creates method to generate suggestions for an username attributes.
Instance Method Details
#suggestions_for(attribute = :username, options = {}) ⇒ 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
23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/username_suggester/suggestions_for.rb', line 23 def suggestions_for(attribute = :username, = {}) first_name_attribute = [:first_name_attribute] || :first_name last_name_attribute = [:last_name_attribute] || :last_name num_suggestions = [:num_suggestions] || 10 send :define_method, "#{attribute}_suggestions".to_sym do suggester = Suggester.new(send(first_name_attribute), send(last_name_attribute), ) name_combinations_with_regex = suggester.name_combinations.map { |s| "^#{s}[0-9]*$" } sql_conditions = Array.new(name_combinations_with_regex.size, "#{attribute} RLIKE ?").join(" OR ") unavailable_choices = self.class.all(:select => attribute, :conditions => [sql_conditions].concat(name_combinations_with_regex)).map{ |c| c.send(attribute) } suggester.suggest(num_suggestions, unavailable_choices) end end |