5
\$\begingroup\$

I was in need of a method to dynamically generate a week range, so that the view reads something like "Week of May 16 - 22" and updates automatically. Here's the helper method I came up with, but I'm wondering if there's a more efficient way to have gone about this.

Dashboards Helper:

def week_range
  today = DateTime.now
  week_start = today.beginning_of_week(:monday).strftime("%B %d")
  week_end = today.end_of_week(:monday).strftime("%d")
  "#{week_start} - #{week_end}"
end

Dashboards View:

<h1>Week of <%= week_range %></h1>

Output:

Week of May 16 - 22

\$\endgroup\$
  • 1
    \$\begingroup\$ Is May 30 - 05 valid, or should it be May 30 - Jun 05? \$\endgroup\$ – tokland May 21 '16 at 22:49
  • \$\begingroup\$ Oh good point @tokland. The way it works now it wouldn't take into account weeks that span multiple months. I guess a change would make would be to conditionally show the month in the second date if it doesn't match the first \$\endgroup\$ – scobo May 21 '16 at 23:27
5
\$\begingroup\$

Your code looks pretty good. Just a couple of details:

  • Instead of hardcoding DateTime.now within the method, add an optional argument. Easier to test and more versatile to use.

  • The month leap is not considered.

I'd write:

def week_range(date: DateTime.now, start_day: :monday)
  start_date = date.beginning_of_week(start_day)
  end_date = date.end_of_week(start_day)
  start_date_string = start_date.strftime("%B %d")
  week_end_string = (start_date.month == end_date.month) ? 
    end_date.strftime("%d") : end_date.strftime("%B %d")  
  "#{start_date_string} - #{week_end_string}"
end
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.