1. 程式人生 > >(GoRails) 自動偵測用戶的時區,使用javascript 的jszt庫。

(GoRails) 自動偵測用戶的時區,使用javascript 的jszt庫。

off rescue time() 24* har ole res not sch

傳統方法見:http://www.cnblogs.com/chentianwei/p/9369904.html

??: 兩個方法最後都要有controller中的類似before_action :set_time_zone來給當前瀏覽器分配時區。

實時方法,根據user的時區設置:

  1. rails new -m template.rb timezone 使用模版,名字用timezone
  2. yarn add jstz #一個javascrit timezone library 可以自動偵測和設置用戶的time zone。技術分享圖片
  3. rails g migration AddTimeZoneToUsers time_zone
  4. rails db:migrate
  5. atom.後打開javascript/packs/application.js(已經安裝使用webpacker)
  6. 輸入import jstz from ‘jstz‘
    1. import jstz from ‘jstz‘
    2. const timezone = jstz.determine()
    3. console.log(timezone.name())
  7. app/views/shared/_head.html.erb
  8. 修改第8行,改為 javascript_pack_tag方法。
  9. 技術分享圖片
  10. 在user註冊頁,f.time_zone_select :time_zone選項,通過它可以在inspect上看到時區的選擇。
  11. 在javascript/packs/application.js設置cookie:

創建函數--設置一個Cookie:

function setCookie(name, value) {

var expires = new Date()

expires.setTime(expires.getTime() + (24*60*60*1000)) #1000天後到期

document.cookie = name + ‘‘=" + value + ‘;expires=‘ + expires.toUTCString()

}

使用這個函數:

setCookie("timezone", timezone.name())

解析這些都是JavaScript的用法,create, Read a Cookie with JavaScript:

var x = document.cookie    獲得當前document的關聯的cookies。

document.cookie = newCookie 設置新的Cookie。

例子:

document.cookie= "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

擴展--JavaScript Cookies:

https://www.w3schools.com/js/js_cookies.asp

  

  12. 在Application.rb中 Controller中定義一個方法 bowser_time_zone

def browser_time_zone

#根據cookies來找到對應的時區,如果沒有則使用Time.zone作為默認,任意錯誤,營救也使用默認

browser_tz = ActiveSupport::TimeZone.find_tzinfo(cookies[:timezone])

ActiveSupport::TimeZone.all.find{ |zone| zone.tzinfo == browser_tz } || Time.zone

rescue TZInfo::UnknownTimezone, TZInfo::InvalidTimezoneIdentifier

Time.zone

end

helper_method :browser_time_zone #添加helper方法

變量browser_tz是如#<TZInfo::DataTimezone: America/Chicago>的對象, 它會和所有TimeZone對象的屬性tzinfo做比較。

#<ActiveSupport::TimeZone:0x00007f97f26b0058 @name="American Samoa", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: Pacific/Pago_Pago>>

  13.在user註冊頁,f.time_zone_select :time_zone選項可以加上這個browser_time_zone helper方法

<%= f.time_zone_select :time_zone, nil, default: browser_time_zone.name %>

技術分享圖片

  14. 瀏覽器顯示時區時間:controller增加一個before_action :set_time_zone, if: :user_signed_in?

def set_time_zone

Time.zone = current_user.time_zone

end

  15 有一個相關gem ‘local_time‘可以利用。

(GoRails) 自動偵測用戶的時區,使用javascript 的jszt庫。