How to start a "week" on a specific day instead of Monday?

In am building app I am trying to start the week from Saturday. In ruby โ€‹โ€‹on rails, the default week starts on Monday.

So if you have a trick or patch to make it work for me!

Thanks in advance!

+2


a source to share


3 answers


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

+9


a source


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

      

+4


a source


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

      

+2


a source







All Articles