gpt4 book ai didi

ruby-on-rails - Rails 自定义渲染器

转载 作者:数据小太阳 更新时间:2023-10-29 08:06:07 26 4
gpt4 key购买 nike

我一直在尝试基于 this Yehuda Katz's blog post 创建自定义渲染器.

如果我调用 render :my_custom_renderer => "index" 它会起作用,但它不适用于默认的 respond_withformat.my_custom_renderer

我创建了一个简单的例子,.

在空白应用中,添加以下行:

在 config/mime_types.rb 中:

Mime::Type.register_alias 'text/html', :my_custom_renderer

在 config/my_custom_renderer.rb 中:

require "action_controller/metal/renderers"
ActionController.add_renderer :my_custom_renderer do |template, options|
self.mime_type ||= Mime::HTML
self.response_body = render_to_string(template).sub(/^/,
'\1<h1>Rendering Injection</h1>')
end

在 app/views/custom_renderer_test/index.my_custom_renderer.erb 中:

<h1>A message "Rendering Injection" should appear above</h1>

在 app/controllers/custom_renderer_test_controller.rb 中:

class CustomRenderingTestController < ApplicationController
def index
respond_to do |format|
# does not go through my custom renderer!
format.my_custom_renderer
# although it works if I explicitly do:
# format.my_custom_renderer { render :my_custom_renderer => 'index' }
end
end
end

最后,在 config/routes.rb 中:

root :to => "custom_rendering_test#index"

启动服务器并转到根页面应该会显示来自 my_custom_renderer 的消息,但实际上并没有。我已经尝试逐步调试 Rails 源代码,但看起来我不太了解渲染架构。

有人可以给我提示问题是什么吗?

最佳答案

可能有帮助的是使用显式方法创建响应器(并使用更新的 respond_with):

class ActionController::Responder
def to_my_custom_renderer
controller.render :my_custom_renderer => controller.action_name
end
end

关于ruby-on-rails - Rails 自定义渲染器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5284443/

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