Generate dyamic 'week of' date range 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:

&lt;h1&gt;Week of &lt;%= week_range %&gt;&lt;/h1&gt;


Output:

Week of May 16 - 22
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