RSS Feed

Refactoring ruby code

Posted on Friday, July 11, 2008 in Refactored Code

I am currently working on a Rails project with a team of developers.
I did some refactoring of a helper method and thought I would share it with the world.
Maybe someone out there can benefit from this.

NOTICE: I changed the helper method name and the model[attribute] values to show a more generic method.

Before refactoring

def some_helper_method
select_tag 'model[attribute]‘,
options_for_select([[" Today ... ", Date.today], Date.today+1,
Date.today+2, Date.today+3, Date.today+4, Date.today+5,
Date.today+6, Date.today+7])
end

After refactoring

def ship_date_select(model,attribute)
todays_date = Date.today
options = [['Today ... ', todays_date]]
6.times do |x|
options << todays_date+x
end
select_tag "#{model}[#{attribute}]", options_for_select(options)
end

The problem with the first example is that it is not very DRY. It is asking Ruby the date 7 times.
It should only need to ask this once and store it in a variable called todays_date. If anyone out there knows a better way to do this please feel free to shoot me an email.

Best,

Tim M.

Leave a Comment

You must be logged in to post a comment.