[英]Alias method chain in ruby calling itself
I am rewriting the controller render method, however, I want to use the old method when in the render_to_string method. 我正在重写控制器的render方法,但是,在render_to_string方法中,我想使用旧方法。 These are my current codes:
这些是我当前的代码:
def render_with_xhr(options = {}, extra_options = {}, xhr_check = true, &block)
if xhr_check && request.xhr?
template = render_to_string(options)
render_without_xhr(:update) {|page| page.replace_html("#popup .dialog", template)}
else
render_without_xhr(options, extra_options, &block)
end
end
alias_method_chain :render, :xhr
What happens is that since render_to_string makes use of render (presumably), I end up in an infinite loop. 发生的事情是,由于render_to_string使用了render(大概),所以我最终陷入了无限循环。 How can I make it fall back to the old method just for that line my new render method?
我如何才能使其仅使用新渲染方法的那条线又回到旧方法?
I tweaked the codes from the accepted answer, final code is below: 我从接受的答案中调整了代码,最终代码如下:
def render_to_string(options = {}, &block)
render(options, {}, false, &block)
ensure
response.content_type = nil
erase_render_results
reset_variables_added_to_assigns
end
def render_with_xhr(options = nil, extra_options = {}, xhr_check = true, &block)
if xhr_check && request.xhr?
template = render_to_string(options)
render_without_xhr :update do |page|
page.replace_html("#popup .dialog", template)
end
else
render_without_xhr(options, extra_options, &block)
end
end
alias_method_chain :render, :xhr
you could at line 2 pass some unique value to options hash, and then detect it in your code and remove 您可以在第2行将一些唯一值传递给options哈希,然后在代码中检测到它并删除
def render_with_xhr(options = {}, extra_options = {}, xhr_check = true, &block)
if xhr_check && request.xhr? && !options.delete(:bacon)
template = render_to_string(options.merge(:bacon => true))
render_without_xhr(:update) {|page| page.replace_html("#popup .dialog", template)}
else
render_without_xhr(options, extra_options, &block)
end
end
alias_method_chain :render, :xhr
like that :) 像那样 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.