ruby 中调用自身的别名方法链
我正在重写控制器渲染方法,但是,我想在 render_to_string 方法中使用旧方法。这些是我当前的代码:
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
发生的情况是,由于 render_to_string 使用了 render(大概),我最终陷入了无限循环。我怎样才能让它回退到旧的方法只是为了那一行我的新渲染方法?
我根据接受的答案调整了代码,最终代码如下:
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
I am rewriting the controller render method, however, I want to use the old method when in the render_to_string method. 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. 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在第 2 行将一些唯一值传递给选项哈希,然后在代码中检测它并
像这样删除:)
you could at line 2 pass some unique value to options hash, and then detect it in your code and remove
like that :)