snippetrubyrailsMinor
Generate dyamic 'week of' date range
Viewed 0 times
rangedyamicdategenerateweek
Problem
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:
Dashboards View:
Output:
Week of May 16 - 22
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}"
endDashboards View:
Week of Output:
Week of May 16 - 22
Solution
Your code looks pretty good. Just a couple of details:
-
Instead of hardcoding
-
The month leap is not considered.
I'd write:
-
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}"
endCode Snippets
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}"
endContext
StackExchange Code Review Q#128974, answer score: 5
Revisions (0)
No revisions yet.