我看到兩個選項來達到你的目標。
第一種方法:聲明ApplicationController
內部和篩選器內部的篩選器,檢查controller_name
和action_name
是否與您的yaml配置中的任何匹配。如果它們匹配,則執行它,如果不忽略。
在代碼想
class ApplicationController
before_filter :start_action_with_check
after_filter :end_action_with_check
def start_action_with_check
c_name, a_name = CONFIG['track1']['start_action'].split(', ')
if c_name == controller_name && a_name == action_name
do_start_action
end
end
...
我希望你的想法。
第二種方法:定義before_filter
的簡潔方法是在模塊中定義它們。通常情況下,您可以使用self.included
方法來定義before_filter
,但當然,您可以有條件地定義它們。例如:
class HomeController < ApplicationController
include StartOrEndAction
...
end
和lib/start_or_end_action.rb
你寫
module StartOrEndAction
def self.included(base)
# e.g. for the start-action
c_name, a_name CONFIG['track1']['start_action'].split(', ')
if c_name == controller_name && a_name == action_name
base.before_filter :do_start_action
end
# and do the same for the after_filter
end
def do_start_action
...
end
def do_end_action
...
end
end
第二解決方案的優點是,before_filter
和after_filter
在需要時僅限定。缺點是您必須將模塊包含到每個控制器中,您可以在其中配置前置過濾器。 第一個優點是可以覆蓋任何控制器,並且可以在檢查前後濾波器時獲得一些額外開銷。
希望這會有所幫助。