Cloudinary Blog

Use Ruby on Rails to Deliver Static Images Via CDN

By Nadav Soferman
Use Ruby on Rails to Deliver Static Images Via CDN
If you heard of Cloudinary before, you probably already know how useful Cloudinary is with managing all your dynamically uploaded images, transforming these to their required dimensions, performing image optimization to ensure files are have the optimal quality and parameters, and delivering them through a fast CDN.
 
But what about all the static images you have in your web application? background images, buttons, icons - they too should be delivered through a Rails CDN, offloading their delivery from your servers and improvixng your website's performance.
 
You can always do it yourself - setup your cloud environment, upload all these static images to your cloud storage, access them through a Rails CDN and make sure to update these images when they change. 
 
Or - you can let Cloudinary do it. Automatically.
 
In this post we wanted to introduce a new Cloudinary feature. This feature simplifies and streamlines the process of uploading your static images to the cloud and delivering them through a Rails CDN.
 
 
page load speed
 
If you haven't done so already - upgrade to our latest Ruby GEM and you will enjoy this new feature with zero code change.
 
How is this done? First, upload all your Ruby-on-Rails applications' static images to Cloudinary, using a single Rake command:
Copy to clipboard
rake cloudinary:sync_static
 
images/logo.png - logo-5740ed843b23d0b86e48081f43a45b9c - Uploading
images/icon_rails.png - icon_rails-74dca949999d8f5960aedfed429711ab - Uploading
images/spinner.gif - spinner-3a0ae382485ddcfc5b57e638baa6005f - Uploading
images/background.png - background-339f8567f25075150cca85d711e94b0c - Uploading
 
Completed syncing static resources to Cloudinary
4 Uploaded
This Rake task finds all the images in all common public folders and in Rails Asset Pipeline’s image asset folders. Afterwards, it uploads all new and modified images to Cloudinary. Uploaded images and their versions are maintained using a local .cloudinary.static file. Make sure you commit this file to your source control.
 
Now that you’ve uploaded all your static images to Cloudinary, all you’ve left to do in order to deliver these through a CDN is to edit your cloudinary.yml file and set the following configuration parameters to ‘true’: 
Copy to clipboard
enhance_image_tag: true
static_image_support: true
That's it. No other code changes required. From now on, every image_tag call in your views would automatically check if the image was uploaded to the cloud (using .cloudinary.static) and if so, would generate a remote Cloudinary CDN URL.
 
For example:
Copy to clipboard
<%= image_tag(“logo.png”, :width => 100, :height => 100) %>
May generate the following HTML code:
Copy to clipboard
<img src="https://res.cloudinary.com/demo/image/asset/
      logo-5740ed843b23d0b86e48081f43a45b9c" width="100" height="100"/>
Keep in mind that you can activate CDN static image support in your production environment while keeping to local files in your development environment.
 
When you add new static images or change existing ones, all you need to do is re-run ‘rake cloudinary:sync_static’.
Copy to clipboard
rake cloudinary:sync_static
 
images/logo.png - logo-5740ed843b23d0b86e48081f43a45b9c - Not changed
images/icon_rails.png - icon-74dca949999d8f5960aedfed429711ab - Not changed
images/spinner.gif - spinner-3a0ae382485ddcfc5b57e638baa6005f - Not changed
images/background.png - background-339f8567f25075150cca85d711e94b0c - Not changed
images/new_icon.gif - new_icon-50f7c240f43256e3f2bfaa3519dab1e8 - Uploading
 
Completed syncing static resources to Cloudinary
4 Not changed, 1 Uploaded
If your website has many static images, you can optimize your site’s load time further by using multiple CDN subdomains. See this blog post for more details on how to activate this feature.
 

CSS & Sass

UPDATE [November 2021]Ruby Sass was deprecated in 2019. The consensus is to use SassC instead. Note that as opposed to Sass, optional named arguments are not supported in SassC, use a hash map instead.

For example:
Sass: cloudinary-url("sample", $quality: "auto", $fetch_format: "auto");

becomes:

SassC: cloudinary-url("sample", ("quality": "auto", "fetch_format": "auto"));
 
The method described above is a powerful way for uploading all static images embedded in your Rails view to the cloud and delivering them through a CDN with no change to your code.
But what about images defined in your CSS or Sass files?
 
If you use the new Asset Pipeline (Rails 3.1+), this would work out-of-the-box. All image-path and image-url in your Sass files would automatically change to remote Cloudinary CDN URLs. For example:
Sass:
Copy to clipboard
.logo
    background-image: image-url("logo.png")
Generated CSS:
Copy to clipboard
.logo { background-image: url(https://res.cloudinary.com/demo/image/asset/logo-5740ed843b23d0b86e48081f43a45b9c) }
So if you already use Asset Pipeline and Sass files, your images will automatically be delivered through a CDN.
 

Transforming static images

One of Cloudinary's major strengths is in its powerful image transformations. In most cases, you'll want your static images displayed as-is. But occasionally, applying transformations on your static images can be very useful. For example, displaying a set of icons in multiple dimensions. Another example is when you want to support Responsive Layout and Images. In this case, adjusting the size of all static images according to your visitors' device resolution might greatly improve your visitors' experience (e.g., resize all images to 50% their original size). 
 
With Cloudinary you can apply various transformations on your static images, with ease.
 
In the following example, we take a 100x100 static logo.png image and resize it on-the-fly to a 50x50 image with rounded corners of 10 pixels radius. The following image_tag:
Copy to clipboard
<%= image_tag("icon_rails.png", :width => 50, :height => 50,
              :crop => :scale, :radius => 10) %>
 
Will generate the following URL:
Copy to clipboard
<img width="50" height="50"
  src="https://res.cloudinary.com/cloudinary/image/asset/
  c_scale,h_50,r_10,w_50/icon_rails-74dca949999d8f5960aedfed429711ab.png"/>
 
Cloudinary offers many more automatic image transformations including image and text overlays, face-detection based cropping and resizing, image format conversion, and even smart categorization, moderation and tagging of images via our partner add ons. All of these can be accessed via the Rails SDK.
 
Changing the look & feel and dimensions of images in your site based on the user’s device can be done using CSS instead of changing your code. This can be be made even simpler if you are using Sass in your Rails project. Simply use the 'cloudinary-url' template method. It will convert image references to remote Cloudinary CDN URLs and can also receive all supported transformation parameters.
 
For example, the following Sass line would generate the same 50x50 scaled logo with rounded corners, via Sass:
Copy to clipboard
background-image: cloudinary-url("rails.png", $width: 50, $height: 50,
                                 $crop: "scale", $radius: 10);
To summarize - if you are using Cloudinary for managing and transforming your uploaded images, you should definitely follow the simple instructions above to immediately experience the performance boost gained by delivering all your static assets through Cloudinary. Don’t have a Cloudinary account yet? Click here to setup a free account in seconds.

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more