2012-02-27 46 views
0

我試圖重寫redirect_to方法來附加PARAM添加到GET請求(如果存在的話,多數民衆贊成)紅寶石。從覆蓋方法

redirect_to方法是在這裏

module ActionController 
................... 

    module Redirecting 
    extend ActiveSupport::Concern 
    include AbstractController::Logger 
    ........................... 

    def redirect_to(options = {}, response_status = {}) #:doc: 
     ............................ 
     self.status  = _extract_redirect_to_status(options, response_status) 
     self.location  = _compute_redirect_to_location(options) 
     self.response_body = "<html><body>You are being <a href=\"# {ERB::Util.h(location)}\">redirected</a>.</body></html>" 
    end 

    end 

end 

下面是如何調用超級我試圖重寫

module ActionController 

    module Redirecting 
     def redirect_to(options = {}, response_status = {}) 

     if options 
      if options.is_a?(Hash) 
      options["custom_param"] = @custom_param 
      else 
      if options.include? "?" 
       options = options + "&custom_param=true" 
      else 
       options = options + "?custom_param=true" 
      end 
      end 
     end 

     super 

     end 

    end 

end 

我顯然是做錯了,和超級方法調用不能工作,我想它的方式。希望有人能幫助。

回答

4

我相信這裏的問題是你正在重新定義redirect_to方法,而不是在新的地方定義。 super不能調用原件,因爲它不再存在。

你正在尋找的方法是alias_method_chain

module ActionController 
    module Redirecting 

    alias_method_chain :redirect_to, :extra_option 

    def redirect_to_with_extra_option(options = {}, response_status = {}) 

     if options 
     ... 
     end 

     redirect_to_without_extra_option(options, response_status) 
    end 
    end 
end 

雖然,我覺得更多的導軌友好的方式將是你的ApplicationController

class ApplicationController 
    .... 
    protected 
    def redirect_to(...) 
     if options 
     .... 
     end 
     super 
    end 
end 

這種方法的好處覆蓋redirect_to是您不打補丁,現在在應用程序控制器中設置了特定於應用程序的參數。

+0

是的,ApplicationController方法就是這樣。謝謝! :) – thanikkal 2012-02-27 17:53:02