Shane Vitarana more brain > blog.html

Acts As Most Popular Rails Plugin

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

This will give you the methods:

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:

=> ["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

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?