Dynamic Image Caching in Rails

I use rmagick gem to create dynamic images from the controller. The controller takes the identifier as a parameter, looks at the model, writes text on top of the existing image and displays it.

I conducted several tests, comparing their generation for each request and writing to disk, and using send_data to output if it already exists. I did not notice much difference in requests / seconds between these two methods.

Is there a better way to cache an image or write it to disk instead of dynamically generating it for each request? Once generated, these images will remain mostly static, but I would also like him to regenerate it after a certain period of time.

+4
source share
3 answers

Best practice is to cache the generated images and allow the web server to serve them.

Use a web server such as Apache or Nginx in front of your Rails application, and make sure that you write the image where the web server can serve it. Therefore, if your Rails route evaluates to /dynamic_images/3.png (which calls dynamic_images_controller action show with id = 3 and format = png), write this image to public/dynamic_images/3.png and use send_file in the controller to send it.

The next time this file is requested ( /dynamic_images/3.png ), the web server will happily serve it (cached), and the Rails application will never suffer.

For advanced needs like re-generating images and flushing controller code, take a look at paperclip gem.

+5
source

Just an idea (never tried): why not store images (especially those that are dynamically generated) using memache?

Rails.cache.write ("MY_IMAGE", image)

+2
source

You must place the cached images in a directory where they will be served by the web server. You do not want to use send_data for this - it is too slow. Also, you probably want to ignore this directory in your VCS.

+1
source

All Articles