Acts As Most Popular Rails Plugin

Posted by shane
on Friday, August 04

Make your models feel like they are in high school again. This plugin retrieves the most frequently occurring values for each column. It adds methods of the form most\popular\[pluralized\_column\_name]. You can control how many results you get with the :limit option. The default limit is 5.

For example, lets say you have a Person model that has a name, age, and city.

class Person < ActiveRecord::Base
  acts_as_most_popular
end

This will give you the methods:

  • most\_popular_names
  • most\_popular_ages
  • most\_popular_cities
For example, lets say you have six people in your database. Three are from Chicago, two from New York, and one from Hartford. Then, most\_popular_cities will give you:
Person.most_popular_cities
=> ["chicago", "new york", "hartford"]

Each most\_popular method returns an array of the type of the column. Check out this unit test for more examples.

Install with:
script/plugin install http://shanesbrain.net/svn/rails/plugins/acts_as_most_popular

Feedback appreciated.

Update: I can’t take credit for the name of this plugin. Someone on the #rubyonrails channel came up with it.

Update: The author of Ruby Inside suggests that this could be used as some sort of Calculation. I think it could easily be made a mode Calculation instead of an Acts As plugin, since popularity is basically the mode in decreasing order. What do you guys think?

Comments

Leave a response

  1. choonkeatAugust 09, 2006 @ 07:02 AM
    How about Person.most_popular_names :scope => :gender
  2. shaneAugust 09, 2006 @ 09:04 PM
    choonkeat... That could be another way to do it. I guess it's just a matter of aesthetics. Takes me back to the render\_partial vs. render :partial debate a while ago. To make it work the way you want, all you have to do is to consolidate all the most_popular methods into one, with if conditions on the passed in scope option. You probably will have to convert the column symbol to a string when passing it to the group\_by. Check out the [source](http://shanesbrain.net/svn/rails/plugins/acts_as_most_popular/lib/acts_as_most_popular.rb).
  3. mikeSeptember 10, 2006 @ 07:37 PM
    the power or ruby is amazing when you think about coding up the same thing using mysql/php commands
Comment