rails 動態時區實作

如何依照不同的條件,例如登入的使用者,來調整預設時區

MarsMars閱讀 1 分鐘
rails 動態時區實作

rails 的 ActiveSupport 有提供 Time 的擴充 method: use_zone ,利用 code block 機制即可實作。

Time.use_zone('Taipei') { Time.current }

如此便可利用 controller 的 around_action 來確保所有或部分的 action 內的預設時區

class ApplicationController
  around_action :set_current_user_timezone!, if: :user_signed_in?

  private
  
  def set_current_user_timezone!(&block)
    Time.user_zone(current_user.timezone, &block)
  end
end      

Mars
關於作者Mars自由接案工程師 | Ruby on Rails

自由接案者、Ruby on Rails 工程師、水肺潛水員、業餘羽球、二胡、鋼琴愛好者。喜歡貓、狗。

延伸閱讀