E17d936d4535519716b6e810052feac5

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)

1
2
3
4
5
6
7
8
9
10
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 !

880cbab435f00197613c9cc2065b4f5a

danielharan

May 9, 2008, May 09, 2008 00:53, permalink

1 rating. Login to rate!

This version is a bit longer, but should be more readable / easier to understand for other team members.

1
2
3
4
5
6
7
8
9
10
11
  # 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
E17d936d4535519716b6e810052feac5

claytonlz

May 9, 2008, May 09, 2008 01:13, permalink

No rating. Login to rate!

Fantastic!

Your refactoring





Format Copy from initial code

or Cancel