The thread about the dates got me kicking myself for not posting to
ask. The website I manage for my kids school that WAS running on php/
joomla got hacked and defaced…so I am taking the opportunity to
learn RonR to set up a new site for them.
On the front page, I need to display the schedule of activities for
the current week. I am having issues figuring out how to get the dates
for the current week (with two seperate definitions: the first is
Sunday through Saturday, the other being Monday through Friday).
I have spent hours pouring over:
The Ruby on Rails Bible
and Ruby on Rails Unleashed
books as well as google but still hitting road blocks.
Can someone help me out and describe to me how to:
Figure out the dates
Display them on the web page. I dont want this stored in the db so
I dont want to add it to my model.
On the front page, I need to display the schedule of activities for
the current week. I am having issues figuring out how to get the dates
for the current week (with two seperate definitions: the first is
Sunday through Saturday, the other being Monday through Friday).
This isn’t really a rails question so I’m not that surprised its not
in the books you’ve listed.
Rails has beginning_of_week, however that is one specific definition
of week. If you have a look inside it’s easy to adapt that.
You just need to look at Time.now.wday, which varies from 0 (on a
sunday) to 6 (on a saturday).
So if your weeks start on thursday then you’re looking for the
previous/next date with a wday of 4. You can do this naively by just
adding a day at a time until some_date.wday has the right value or you
can work out the increments yourself.
it’s just arithmetic modulo 7. if d is the number of days until the
next thursday, and n is Time.now.wday then it must be that
n+d = 4 [7]
so d = 4-n [7]
ie d = 4-n +k*7
for an appropriate value of k.
So days until thursdays are given by d=4-n + k*7.
If you want the next thursday then that imposes 7>=d >0
so if 0 <= n <4 (ie today is sunday through wednesday) then k = 0, so
d = 4 - Time.now.wday
if n>= 4 (thursday through saturday) then k = 1 so d = 11 -
Time.now.wday
and similarly for finding the previous thursday (this is probably an
overcomplicated way of reasoning about this - showing my background
here)