问题
I've been trying to create a custom renderer based on this Yehuda Katz's blog post.
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:
In config/mime_types.rb:
Mime::Type.register_alias 'text/html', :my_custom_renderer
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
In app/views/custom_renderer_test/index.my_custom_renderer.erb:
<h1>A message "Rendering Injection" should appear above</h1>
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
And, finally, in config/routes.rb:
root :to => "custom_rendering_test#index"
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?
回答1:
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
来源:https://stackoverflow.com/questions/5284443/rails-custom-renderer