Цепочка псевдонимов в 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

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

как это:)

Другие вопросы по тегам