[英]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.