In Jamis Buck's and Michael Koziarski's
The Rails Way keynote this morning, they talked about improving code as they do on the
Rails Way blog. For one snippet, they changed this:
class SomeModel
def before_save
if created_at == Time.now.to_date.to_time
created_at = Time.now
end
end
end
into this:
class SomeModel
before_save :make_created_now_if_created_today
def make_created_now_if_created_today
if created_at = Time.now.beginning_of_day
created_at = Time.now
end
end
end
One key point was the readability that ActiveSupport provides.
Time.now.beginning_of_day shows much more intent than
Time.now.to_date.to_time.
The method name
make_created_now_if_created_today caught my attention. Many developers (myself included) would have used something less descriptive. Maybe
update_created_at or something worse like
adjust_time. So what is an easy way to know the method is well named? Write a test for it. Here are the potential test names:
def test_adjust_time_makes_created_now_if_created_today
def test_update_created_at_makes_created_now_if_created_today
def test_make_created_now_if_created_today_makes_created_now_if_created_today
When you're trying to describe what the method should do and it matches the name of the method, that's a good thing.