Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching dynamic images in Rails

I am using the rmagick gem for generating dynamic images from a controller. The controller takes an id as a param, does a look up on a model, writes text over an existing image, and outputs it.

I have run some benchmarks comparing generating it for every request versus writing to disk and using send_data to output it if it already exists. I haven't noticed much of a difference in requests/second between these two methods.

Is there a best practice for caching the image or writing it to disk instead of generating it dynamically for every request? Once generated, these images would remain mostly static but I would also like the option to re-generate it after a certain time interval.

like image 500
Trevor Avatar asked Feb 28 '23 23:02

Trevor


2 Answers

The best practice is to cache generated images and allow the webserver to serve them.

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

The next time that file is requested (/dynamic_images/3.png), the webserver will gladly serve it (cached) and the Rails app will never get hit.

For advanced needs, like re-generating the images, and cleaning up your controller code, have a look at the paperclip gem.

like image 120
Jonathan Julian Avatar answered Mar 08 '23 18:03

Jonathan Julian


Just an idea (never tried): why not store images (especially the ones that are dynamically generated) with memache?

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

like image 33
Philipp Bolliger Avatar answered Mar 08 '23 20:03

Philipp Bolliger