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 == Date.today.yday
    @alternate_odd_even_state = 'birthday_today'
  elsif (birthdate.yday >= (Date.today.yday - 7) && birthdate.yday < Date.today.yday)
    @alternate_odd_even_state = 'birthday_past'
  elsif (birthdate.yday <= (Date.today.yday + 7) && birthdate.yday > Date.today.yday)
    @alternate_odd_even_state = 'birthday_future'
  else
    @alternate_odd_even_state = even_odd ? 'even' : 'odd'
  end
end

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 = Date.today.yday
  case birthdate.yday
  when today
    'birthday_today'
  when (today - 7) .. today
    'birthday_past'
  when today .. (today + 7)
    'birthday_future'
  else
    even_odd
  end
end

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