Rail 3 custom renderer: where to put this code?

I follow Yehuda’s example on how to create my own rendering for Rails 3, according to this post: http://www.engineyard.com/blog/2010/render-options-in-rails-3/

My code works for me, but it's hard for me to understand where this code should live. Right now, I have my code stuck right in my controller file. By doing this, everything works. However, when I move the code to the lib folder, I explicitly β€œrequire” my file in the controller, which needs a renderer, or it will not work. Yes, the file loads when it sits in the lib folder automatically. but the code for adding a renderer does not work for any reason, as long as I don't require it.

Where should I put my code to add the type of rendering and mime so that rails 3 picks it up and registers it for me, without having to manually request a file in my controller?

+4
source share
3 answers

I would put it in the initializer or in lib and require it in the application controller.

+1
source

In Jose Valim's book , Creating Rails Applications , this is the first chapter. It creates mime type and PDF rendering using Prawn.

In his example, he created lib/pdf_renderer.rb as follows:

 require "action_controller" Mime::Type.register "application/pdf", :pdf 

Since lib no longer loaded by autoload, you will either have to autoload lib , or simply require this file in which you want to use it.

An initializer may also be appropriate here.

+1
source

I did something else about this, based on the suggestions here.

I found that the "mime_types" initializer was already in our code base. I think this is created by rails by default. there were several examples seen. so I added my own mime type to this file.

I also decided to use an initializer for a custom renderer so that it automatically loads and is accessible with the application. therefore, I must not forget to include it in the various places that I need. I can simply reply_ to the format I created and send the data down.

Thanks for the advice, everyone.

0
source

Source: https://habr.com/ru/post/1340017/


All Articles