watch this  

the official mrchucho blog

My Rails Way

Posted 2007 Jan 26

Inspired by my new favorite Rails site, The Rails Way, I’m posting a little Rails refactoring I did recently.

In a nutshell, a different CSS class needs to be applied to a row depending on birthday. Otherwise, use standard Zebra rows (via even_odd helper). Previously, the code looked like this:

def even_odd_or_birthday(birthdate)
  if birthdate == nil
    @alternate_odd_even_state = even_odd ? 'even' : 'odd'
  elsif birthdate.yday ==
    @alternate_odd_even_state = 'birthday_today'
  elsif (birthdate.yday >= ( - 7) && birthdate.yday <
    @alternate_odd_even_state = 'birthday_past'
  elsif (birthdate.yday <= ( + 7) && birthdate.yday >
    @alternate_odd_even_state = 'birthday_future'
    @alternate_odd_even_state = even_odd ? 'even' : 'odd'

Besides being incorrect, it seemed cumbersome and not very Ruby-like. Note that the granularity required is only a day, not time. Next is what I’ve come up with instead:

def even_odd_or_birthday(birthdate)
  return even_odd if birthdate.nil?
  today =
  case birthdate.yday
  when today
  when (today - 7) .. today
  when today .. (today + 7)

Though it isn’t any shorter, it reads a more naturally to me. Any improvements or suggestions?

Responses to "My Rails Way"

No responses yet.

Comments are now closed.
atom rss