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.
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.
Just an idea (never tried): why not store images (especially the ones that are dynamically generated) with memache?
Rails.cache.write("MY_IMAGE", image)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With