def Expense.get_top_n_categories options={}
sQuery = "SELECT categories.name, sum(amount) as total_amount
from expenses
join categories on category_id = categories.id
group by category_id
order by total_amount desc";
sQuery += " limit #{options[:limit].to_i}" if !options[:limit].nil?
Expense.find_by_sql(sQuery)
end
# Now you see a param.. top 10
obCategories = Expense.get_top_n_categories :limit => 10
# now you don't
obCategories = Expense.get_top_n_categories
The cleverness lies in defaulting the options param to an empty hash. Now you can pass any number of params using the param => value notation.. everything comes neatly packaged to you as an options hash.
How did you manage to get the code formatted so pretty? http://blog.wolfman.com/articles/2006/05/26/howto-format-ruby-code-for-blogs
No comments:
Post a Comment