class Article < ActiveRecord::Base
# Find all articles in the given date range based on the published_at field
def self.find_archived(year, month="January")
start_date = Date.parse("#{month}/01/#{year}")
end_date = (month == "January") ? start_time + 1.years : start_date + 1.months
self.find(:all, :conditions => {:published_at => start_date .. end_date})
end
end
Refactorings
No refactoring yet !
danielharan
May 9, 2008, May 09, 2008 00:53, permalink
This version is a bit longer, but should be more readable / easier to understand for other team members.
# Find all articles in the given date range based on the published_at field
def self.find_archived(year, month=nil)
if month.nil?
start_date = Date.parse("01/01/#{year}")
end_date = start_date + 1.year
else
start_date = Date.parse("#{month}/01/#{year}")
end_date = start_date + 1.month
end
self.find(:all, :conditions => {:published_at => start_date .. end_date})
end
I've got a route that handles things like: /articles/2008/05 => "all articles from may 2008" and /articles/2008 => "all articles from 2008". I needed to create a date range that would either be the year and month that was passed plus one month, or the year that was passed plus one year. I went with the hackish way of setting the month to "January" if it was not passed since I'm guessing I'll never call this function like Article.find_archived("2008", "April") so checking for "January" later on works, for now. (EDIT: My original snippet didn't actually work, but this does)