Rails 自定义渲染器
我一直在尝试基于 这篇 Yehuda Katz 的博文.
如果我调用 render :my_custom_renderer =>"index"
,但它不适用于默认的 respond_with
或 format.my_custom_renderer
It works if I call render :my_custom_renderer => "index"
, but it doesn't work with default respond_with
or format.my_custom_renderer
我创建了一个简单的例子.
I created a simple example, .
从一个空白的应用程序中,添加以下几行:
From a blank app, add the following lines:
在 config/mime_types.rb:
In config/mime_types.rb:
Mime::Type.register_alias 'text/html', :my_custom_renderer
在 config/my_custom_renderer.rb 中:
In 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 中:
In 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 中:
In 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 中:
And, finally, in config/routes.rb:
root :to => "custom_rendering_test#index"
启动服务器并转到根页面应该会显示来自 my_custom_renderer 的消息,但它不会.我已经尝试逐步调试 Rails 源代码,但看起来我不太了解渲染架构.
Starting up a server and going to the root page should display the message from my_custom_renderer, but it does not. I've tried debugging Rails source step by step, but looks like I don't understand rendering architecture well-enough.
有人可以告诉我问题是什么吗?
Can someone please give me a hint on what the problem is?
使用显式方法创建响应器(并使用较新的 respond_with
)可能会有所帮助:
What might help is to create a responder (and use the newer respond_with
) with the explicit method:
class ActionController::Responder
def to_my_custom_renderer
controller.render :my_custom_renderer => controller.action_name
end
end