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

200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 21, 2016 at 21:30
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is May 30 - 05 valid, or should it be May 30 - Jun 05? \$\endgroup\$ Commented May 21, 2016 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\$ Commented May 21, 2016 at 23:27

1 Answer 1

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
answered May 22, 2016 at 9:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.