Reputation: 1098
Hey All, I am using Rails 3 and the Chronic gem (for date parsing) and need to create a select list of Sundays for the past 6 months. Here is what I have so far:
<%
# weeks in 6 months = 26
week = 1
sunday = Date.parse( Chronic.parse('this sunday').to_s )
sunday_array = []
while week <= 26
sunday_array << sunday - ( week * 7 )
week += 1
end
%>
<%= select_tag 'sunday', options_for_select( sunday_array ) %>
Does anybody know a better / cleaner way of doing this? Thanks.
Upvotes: 0
Views: 355
Reputation: 15408
You can play code golf with...
sunday = Date.parse( Chronic.parse('this sunday').to_s )
sunday_array = []
26.times { |i| sunday_array << sunday - ( i * 7) }
And then get rid of your magic numbers....
NUM_SUNDAYS = 26
sunday = Date.parse( Chronic.parse('this sunday').to_s )
sunday_array = []
NUM_SUNDAYS.times { |i| sunday_array << sunday - ( i * 7) }
And obviously, you would move it into a helper method so it's not sitting in your ERB. :)
Upvotes: 1