2012-01-10 28 views
1

我想讓after_update回調只在特定配置參數爲true時執行。 起初,我有這樣的事情:以配置參數爲條件進行ActiveRecord回調並對其進行測試

after_update :do_something 
... 

def do_something 
    return unless MyApp::Application.config.some_config 
    actualy_do_something 
end 

但轉念一想,爲什麼不把回調分配條件? 這樣的:

after_update :do_something if MyApp::Application.config.some_config 

但是,我不完全明白我在這裏做什麼。這個改變何時會發生?只有在服務器重新啓動?我如何測試這種行爲?我不能只是設置配置,模型文件將不會再被讀取。

請指教。

回答

5

實現有條件的回調的標準方法是通過符號或PROC到:if

before_create :generate_authentication_token, :if => :authentication_token_missing? 
after_destroy :deliver_thank_you_email, :if => lambda {|user| user.wants_email? } 

def authentication_token_missing? 
    authentication_token.empty? 
end 

此格式還可以引用全局配置上Rails.configuration

after_update :refresh_cache, :if => :cache_available? 

def cache_available? 
    Rails.configuration.custom_cache.present? 
end 

這將允許設置應用程序的行爲而不必重新啓動服務器或刪除常量並重新加載文件。

相關問題