Most people know of named_scope, but they don’t understand the power of it in conjunction with lambda. Well, I was in a situation where I needed to fetch reports based on a day, month, year and combination. Here is an example of how I need to call my reports:
1 2 3 | Report.date(2009).all # by year Report.date(2009, 07).all # by year and month Report.date(2009, 07, 17).all # by year, month, and date |
The named_scope for this monstrosity is:
1 2 3 4 5 6 7 8 | named_scope :date, lambda { |*date| conditions = case date.size when 1 then ["YEAR(date) = ?"] when 2 then ["YEAR(date) = ? AND MONTH(date) = ?"] when 3 then ["YEAR(date) = ? AND MONTH(date) = ? AND DAY(date) = ?"] end { :conditions => conditions | date } } |
The “conditions | date” simply merges the two arrays together. There are certainly cleaner ways to do this, but this was a quick, simple example, of the power of named_scope.
No related posts.