ActiveSupport::TimeZone; 功能:用戶自行選擇時區。

TimeZone類做爲一個包裝器,服務一個TZinfo::Timezone 實例。html

 

用途:app

134個時區的檢索。ui

使用簡化的英文單詞來取回和顯示時區:如"Beijing" => "Asia/Shanghai"。url

惰性加載TZInfo::Timezone實例。spa

建立ActiveSupport::TimeWithZone實例,經過parse , local, at, now方法設計

 

設置:orm

application.rb:htm

class Application < Rails::Applicationstring

  config.time_zone = 'Beijing'it

end

Time.zone      輸出一個實例變量

Time.zone.name 輸出 「Beijing」

Time.zone.now   輸出一個TimeWithZone實例 Thu, 26 Jul 2018 09:27:24 CST +08:00 

 

✅,TimeWithZone實例 使用Ruby Time實例的相同的API方法。 


 

 

建立根據用戶的配置,來切換時區:

  1. 給User新增一列, time_zone: string (Model)
  2. 一個操做選擇timeZone的功能和界面。(routes, view, controller)
  3.  每次登錄後,根據user的time_zone來設置時區。(controller)

第二步詳解:

  1. 設置routes :  resource :user
  2. rails g controller users 設置edit, update方法
  3. add edit.html.erb 新增一個form:

<div class="form-group">
  <%= f.label :time_zone %>
  <%= f.time_zone_select :time_zone,  /Beijing/ %>  ⚠️:time_zone_select方法是formbuilder方法。
</div>

最後一步:

在application控制器中:

before_action :set_timezone

def set_timezone

  if current_user && current_user.time_zone

     Time.zone = current_user.time_zone

  end

end

 

 

關於設置resource :user

解釋:不加S,生成不帶id的url。沒有index_action。

設計的緣由:前臺用戶更改的是自身的內容,無需id來判斷本身和他人的區別。同時網址也不會帶id,隱祕性好(無需特地設置網址亂數)。

new_user     GET    /user/new(.:format)    users#new
edit_user     GET    /user/edit(.:format)     users#edit
user        GET    /user(.:format)       users#show
     PATCH/PUT   /user(.:format)       users#update
         DELETE       /user(.:format)       users#destroy
             POST      /user(.:format)       users#create

相關文章
相關標籤/搜索