在 MVC 架構中,Controller 處理應用邏輯與資料存取。Rails 的 ActionController 提供四大核心服務:URL 映射、Session 追蹤、過濾與驗證、頁面快取。本文詳細解析各服務運作原理與實作範例。
輸入 https://localhost:3000/demo/say/hello 後:
app/controllers/say_controller.rb(僅首次)SayControllerapp/helpers/say_helper.rb(若存在),混入 Helper 方法app/models/say.rb(若存在)設定於 config/routes.rb:
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/service.wsdl', :action => 'wsdl'
map.connect ':controller/:action/:id' # 預設路由
end
URL 分為三段::controller/:action/:id。/demo/admin/show/1 映射為:
:controller => 'admin', :action => 'show', :id => 1
Rails 自動呼叫 AdminController#show(1)。
Rails 透過 cookies[] 與 session[] 類陣列介面,無需顯式建立物件:
class CookiesController < ApplicationController
def create_cookie
cookies[:the_time] = Time.now.to_s
redirect_to :action => "action_two"
end
def get_cookie
render :text => " #{cookies[:the_time]}"
end
end
class SessionController < ApplicationController
def login
user = User.find_by_name_and_password(params[:user], params[:password])
if user
session[:user_id] = user.id
redirect_to :action => "index"
else
reset_session
flash[:note] = "帳號或密碼錯誤!"
end
end
end
flash 為一次性 Session 資料,重導向後自動清除,適合提示訊息。
def authorize
unless session[:user_id]
flash[:notice] = "請登入"
redirect_to :controller => "login", :action => "login"
end
end
class AdminController < ApplicationController
before_filter :authorize # 所有 Action 前執行
# after_filter :log_access # 所有 Action 後執行
end
class BlogController < ApplicationController
verify :only => :post_comment,
:session => :user_id,
:add_flash => { :note => "請先登入才能留言" },
:redirect_to => :index
end
僅針對 post_comment Action,檢查 Session 有 user_id,否則導向首頁並顯示訊息。
針對高頻、低變動頁面,使用 caches_page:
class ContentController < ApplicationController
before_filter :verify_premium_user, :except => :public_content
caches_page :public_content # 產生靜態 HTML 至 public/ 目錄
end
快取層次:caches_page(整頁靜態化)、caches_action(Action 層級)、cache(片段快取)。
map.resources :posts # 自動生成 7 條 RESTful 路由
# GET /posts -> index
# GET /posts/new -> new
# POST /posts -> create
# GET /posts/:id -> show
# GET /posts/:id/edit -> edit
# PUT /posts/:id -> update
# DELETE /posts/:id -> destroy
ActionController 將 Web 應用的通用關注點(路由、Session、認證授權、快取)封裝為聲明式 API,讓開發者專注於業務邏輯。掌握 before_filter、verify、caches_page 三大工具,即可處理 80% 的 Controller 層需求。