CDN in Active Storage
The purpose of a CDN is to deliver content faster to users, how? Decreasing the latency of a request using servers that are closer to the user. Imagine that YouTube is a Japanese company and they have all their servers there. For someone from Spain, the user experience would be incredible slow! This means: users get annoyed = conversions drop = loss money
Let’s see how to pass all our uploaded files from Active Storage through a CDN.
Inside our config/routes.rb
we have to add an URL helper, also called direct:
direct :cdn do |blob|
if Rails.env.development? || Rails.env.test?
route = blob.is_a?(ActiveStorage::Variant) ? :rails_representation : :rails_blob
route_for(route, blob)
else
File.join(Rails.application.credentials.cloudfront_url, blob.key)
end
end
To use it you can pass the new route to any Active Storage object:
<%= image_tag cdn_url(@user.avatar) if @user.avatar.attached? %>