开发者

Looping through weeks of the year in Ruby (Sinatra)

I'm creating a very simple timeshare application using Sinatra and Datamapper. Every user in the application will have n reservations and for the time being each reservation runs from Monday to Sunday and there can only be one reservation per week.

Now I will need a view with a textbox (and label) for each week of the year where the users will put their name (through autocompletion or something) and thereby creating a reservation for that week. And if the week is reserved the name will of course be filled in the textbox (and disabled)

It would be something like

weeks.each do
  find user that has reserved this week - and create a textbox
end

So my question I guess is as simple - how d开发者_如何学编程o I loop through all weeks of a year in Ruby?

Or would it be a better solution to just loop 52 times and make an array for each user with the numbers of reserved weeks in it?


You should loop through this:

(Date.beginning_of_year.cweek...Date.today.end_of_year.cweek).each do |week|
  find user that has reserved this week - and create a textbox
end


(1..52).each do |week|
   # find user that has reserved this week - and create a textbox
end


For others that might find this old question, like I did...

January 1 is sometimes week 53. December 31 is sometimes week 1. If you want to loop through all the weeks of the year, you must first decide if you want the first days of january, even when it could be the previous year's week 53.

To get the highest week-number in a year, you can always check december 28 (since ISO-weeks state that week 1 is the week with the first thursday).

If you don't care about the first days of january (might be fri-sun), you might do something like:

require 'date' # Already included in sinatra though

(1..Date.parse("#{year}-12-28").cweek).each do |week|
  puts week
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜