Local CDN

Local CDN simplifies the inclusion of external stylesheets and JavaScript from various content delivery networks (CDNs), and uses local alternatives for local requests in development mode so your site loads faster, and looks right even when you don’t have an Internet connection (eg, on an airplane).

Local CDN is compatible with Rails 2.x and Rails 3.

1. Install

As a Gem (on Rails 3)

Add this to your Gemfile:

gem "local_cdn"

and run this at the command prompt:

bundle install

Or As a Plugin

At the command prompt:

rails plugin install git://github.com/alexreisner/local_cdn.git

2. Configure

You have to tell LocalCDN the URLs of the CDNs you’re using: the remote (normal) URLs and the local (mirror) URLs. You do this in two separate config files:

config/cdn.remote.yml
config/cdn.local.yml

These files might look something like this:

# cdn.remote.yml
google: "http://ajax.googleapis.com/ajax/libs/"
yahoo:  "http://yui.yahooapis.com/"

# cdn.local.yml
google: "http://localhost/cdn_mirror/google/"
yahoo:  "http://localhost/cdn_mirror/yahoo/"

Be sure to include the trailing slashes!

Having two separate config files might seem tedious, but there is a good reason for it: developers may keep their local CDN mirrors in different places on their computers. Hence you should check cdn.remote.yml into your source code repository, but not cdn.local.yml. Your application will run just fine without cdn.local.yml: remote URLs will be used. If a developer wishes, they can set up a local mirror and create cdn.local.yml.

To set up a local CDN mirror, see: github.com/alexreisner/cdn_mirror

3. Use

To use LocalCDN you must change your stylesheet and javascript inclusion tags slightly. Prepend cdn_ to the method name and add a new first argument which is the name of the desired CDN (as a symbol), as specified in cdn.remote.yml. For example, if you’re currently loading jQuery from Google’s CDN you probably have something like this:

<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" %>

To ensure that jQuery still gets served when you don’t have a network connection, you would change the above tag to the following (assuming you have the above entry for google in your cdn.remote.yml:

<%= cdn_javascript_include_tag :google, "jquery/1.4.3/jquery.min.js" %>

Needless to say, you must also make sure the file is available locally at http://localhost/local_cdn/jquery/1.4.3/jquery.min.js. Again, to set up a local CDN mirror, see: github.com/alexreisner/cdn_mirror

Copyright © 2009-10 Alex Reisner, released under the MIT license