Generate a select list of sundays in Rails 3
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:
<开发者_如何学JAVA%
# 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.
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. :)
精彩评论