gpt4 book ai didi

ruby-on-rails - 在 rails 中禁用自动渲染

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:18 24 4
gpt4 key购买 nike

我需要的是禁用 rails 中的自动页面 (HTML) 呈现并使用 after_action 方法覆盖它。我想要达到的效果相当于 CakePHP $this->autoRender = false;

应用程序 Controller .rb

class ApplicationController < ActionController::Base

after_action :custom_render

layout nil # Tried this but didn't worked

def custom_render
render #[...]
end


end

some_controller.rb

class SomeController < ApplicationController

def index
# No rendering here
end

end

如代码所示,我尝试添加一个布局 nil 以防止呈现所有操作,但这似乎并不影响操作的行为。

最佳答案

尚未检查它是否适用于 Rails 4,但此补丁适用于 Rails 5。

根据BasicImplicitRender的代码和 ImplicitRender , send_action 的是BasicImplicitRender 负责调用default_render

文档说:

For API controllers, the implicit response is always 204 No Content.

For all other controllers, we use ... heuristics to decide whether to render a template, raise an error for a missing template, or respond with 204 No Content ...

所以我想重新定义 default_render 方法会达到你的目的。

在你的 Controller 中:

def a
# uses `default_render` unless you call `render` method explicitly
end

def b
render plain: 'Custom text for b' # `default_render` won't be called
end

private

# This does the trick
#
def default_render
render plain: 'Text'
end

你也可以破解 send_action 就像 it is done in Rails甚至完全跳过 default_render 调用:

module ActionController
module BasicImplicitRender # :nodoc:
def send_action(method, *args)
# super.tap { default_render unless performed? }
super
end
end
end

关于ruby-on-rails - 在 rails 中禁用自动渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com