【问题标题】:Alias method chain in ruby calling itselfruby 中的别名方法链调用自身
【发布时间】:2010-06-09 12:52:40
【问题描述】:

我正在重写控制器渲染方法,但是,我想在 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 使用了渲染(大概),我最终陷入了无限循环。我怎样才能让它回退到旧方法,只是为了那行我的新渲染方法?

我根据接受的答案调整了代码,最终代码如下:

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

【问题讨论】:

    标签: ruby-on-rails alias-method-chain


    【解决方案1】:

    您可以在第 2 行将一些唯一值传递给选项哈希,然后在您的代码中检测并删除它

    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
    

    像这样:)

    【讨论】:

    • 感谢redditor,我会尝试并报告=)
    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多