Another simple case of "this took longer than it takes to look up this issue on Google" :)
Here is the configuration we ended up using, which works perfectly:
The advantage of this approach, is that with several CDN hosts (which are useful to increase speed of browser's parallel download of images), this allows you to generate a consistent URL for each file instead of a random one. So a file with name "image.jpg" will always generate "cdn-s3-2.ourdomain.com" because of simple assignment:
CarrierWave is a fantastic and well supported ruby gem for managing images, including support for cloud storage like Amazon.
Whether or not you use CarrierWave on the cloud, you almost always want to put your user-uploaded images behind a CDN. There are many CDNs available, including Amazon's CloudFront, Fastly.com, CacheFly, Akamai, etc, and comparing them is outside the scope of this article.
Whether or not you use CarrierWave on the cloud, you almost always want to put your user-uploaded images behind a CDN. There are many CDNs available, including Amazon's CloudFront, Fastly.com, CacheFly, Akamai, etc, and comparing them is outside the scope of this article.
Because browsers, especially older, are limited in how many connections they will establish to a single host, it is sometimes beneficial to have images load from several alternating URLs, for example:
http://cdn-0.wanelo.com http://cdn-1.wanelo.com http://cdn-2.wanelo.com
etc...
CarrierWave supports fog_host variable which can be set to either a string (a static hostname), or a lambda (if for example a randomized string is desired) and the usage is well described here.
Unfortunately, due a bug that is not yet fixed (and unclear if it will be), you currently can not use the file object directly inside the lambda as it's shown in the examples.
If you actually want to use the "file" object inside the fog_host proc in any way, then fog_host must be a double-lambda, because the first lambda gets called by the accessor created in Configuration class. The second is then called in public_url instance method.
Here is the configuration we ended up using, which works perfectly:
config.fog_host = lambda do
lambda do |file|
host_number = file.path.sum % 4
"cdn-s3-%d.ourdomain.com" % host_number
end
end
"image.jpg".sum % 4
=> 2
Comments