簡體   English   中英

紅寶石。 從重寫方法調用Super

[英]Ruby. Calling Super from the overriden method

我正在嘗試重寫redirect_to方法,以將其他參數添加到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 

我顯然做錯了,超級方法調用無法按我想要的方式工作。 希望有人可以幫忙。

我相信這里的問題是您正在重新定義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

雖然,我認為更Rails友好的方法是在ApplicationController重寫redirect_to

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

這種方法的好處是您無需修補導軌,並且現在在應用程序控制器中設置了特定於應用程序的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM