Rail 3 custom renderer: where do put this code?
I'm following along with Yehuda's example on how to build a custom renderer for Rails 3, according to this post: http://www.engineyard.com/blog/2010/render-options-in-rails-3/
I've got my code working, but I'm having a hard time figuring out where this code should live. Right now, I've got my code stuck right inside of my controller file. Doing this, everything works. When I move the code to the lib folder, though, I have explicitly 'require' my file in the controller that needs the renderer or it won't work. Yes, the file gets loaded when it sits in the lib folder, automatically. but the code to add the renderer isn't working for some reason, until I do a require on it.
where should I put my code to add the renderer and mime type, so that rails 3 will pick it up and register it for me, without me having to manually require the file in my contro开发者_高级运维ller?
I'd put it in an initializer, or in lib and require it in application controller.
In Jose Valim's book, Crafting Rails applications, this is the first chapter. He creates a PDF mime type & renderer using Prawn.
In his example, he created lib/pdf_renderer.rb
with this:
require "action_controller"
Mime::Type.register "application/pdf", :pdf
Since lib
is no longer autoloaded, you'll either have to autoload lib
or specifically require this file where you want to use it.
An initializer might also be appropriate here.
i did some more digging around on this based on the suggestions here.
i found a "mime_types" initializer was already in our code base. i think this is created by rails, by default. it had several commented out examples in it. so i added my custom mime type to this file.
i also decided to use an initializer for the custom renderer so that it's automatically loaded and available with the app. this way i don't have to remember to include it in the various places i need it. i can just respond_to the format i created, and send the data down.
thanks for the tips, everyone.
精彩评论