Skip to content

Instantly share code, notes, and snippets.

@renato-zannon
Created September 20, 2011 13:53
Show Gist options
  • Save renato-zannon/1229110 to your computer and use it in GitHub Desktop.
Save renato-zannon/1229110 to your computer and use it in GitHub Desktop.
A simple practice to help your fellow workers navigate your dynamic ruby code
# It's common, while creating a bunch of very similar methods, to create
# a loop to define them all at once. (Very simple) example follows:
week_days = %w[sunday monday tuesday wednesday thursday friday saturday]
week_days.each do |day|
define_method("events_on_#{day}") do
events.select { |event| event.day == day }
end
end
# Okay, now we have 7 methods (events_on_monday, events_on_tuesday etc).
# However, we have a problem here (actually, more than one, but let's forget
# the OO issues for a sec): When someone needs to take a look at any of these
# methods' definition, they won't be able to find it by simple grep'ing, since
# the string "def events_on_saturday" isn't defined anywhere.
#
# To diminish that problem without having to drop to good (?) ol' CTRL+C
# CTRL+V, my solution is to put a few comments before the loop, so that if
# someone looks for the method definition by text search, they will end up in
# the loop. Using this "technique", the above code becomes:
week_days = %w[sunday monday tuesday wednesday thursday friday saturday]
# def events_on_sunday
# def events_on_monday
# def events_on_tuesday
# def events_on_wednesday
# def events_on_thursday
# def events_on_friday
# def events_on_saturday
week_days.each do |day|
define_method("events_on_#{day}") do
events.select { |event| event.day == day }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment