I am in Rails 6.1 (I assume there are no major changes in Rails 7)
I have a lot of videos in my system, and I am showing previews of them in the index view.
I use this:
<%= image_tag play_session.video.preview(resize_to_limit: [640, 360]) %>
And it works well. But the first time it is called it takes a lot of time:
Disk Storage (13737.8ms) Downloaded file from key: toyqvx3f980aqhh2l9uyno2cqp9e
And if I have several videos the time can be minutes.
It is worth saying that the second time the index is called. All the previews are there already. ActiveStorage makes some black magic that when a preview is generated it is persisted for future use.
I would like to pregenerate the previews so they are ready when the index is called.
Is this possible? or there is another pattern I should be using?
Rails recommend to avoid processing previews synchronously in views
You can add some asynchronous scheduled job (for example with Sidekiq) and invoke such code (of course you can add needed conditions)
PlaySession.find_each do |play_session|
play_session.video.preview(resize_to_limit: [640, 360]).processed
end
Processing a preview generates an image from its blob and attaches the preview image to the blob. Because the preview image is stored with the blob, it is only generated once
This way you will pregenerate previews