How to start a "week" on a specific day instead of Monday?
I managed to make a pull request to rails and now you can pass the symbol argument to the method beginning_of_week
. For example, beginning_of_week(:sunday)
will give you Sunday, assuming the week starts on Sunday. The same goes for the method end_of_week
. But you have to wait for rails 3.2 to come out, unless you are on the edge of bleeding.
See this for more information: https://github.com/rails/rails/pull/3547
UPDATE: Now I'm waiting for the new PR to be accepted, it allows you to set an initial weekly start in your rails config file. See this for more info https://github.com/rails/rails/pull/5339
UPDATE:
Combined!
rafaelfranca merged commit 5428de1 into rails:master from gregolsen:week_start_config 4 months ago
Closed rafaelfranca closed the pull request 4 months ag
about
a source to share
You can throw this into the initializer to beginning_of_week
return on Sunday:
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Time #:nodoc:
module Calculations
def beginning_of_week
(self - self.wday.days).midnight
end
end
end
end
end
It is safer, however, for you to define your own method and leave the margin alone:
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Time #:nodoc:
module Calculations
def traditional_beginning_of_week
(self - self.wday.days).midnight
end
end
end
end
end
a source to share
You can try to change the methods Date#wday
and Time#wday
on your own. I think Rails support methods like beginning_of_week
etc rely on wday and will work out of the box.
Here's some code, but it's definitely just an idea, neither tested nor recommended:
require 'activesupport'
#=> true
Time.now.wday
#=> 4
Time.now.beginning_of_week
#=> 2010-04-19 00:00:00 0200
class Time
alias_method :orig_wday, :wday
def wday
(self.orig_wday + 2) % 7
end
end
Time.now.wday
#=> 6
Time.now.beginning_of_week
#=> 2010-04-17 00:00:00 0200
a source to share