Skip to content
This repository has been archived by the owner on Apr 4, 2018. It is now read-only.

Commit

Permalink
Added Ruby helper; added README
Browse files Browse the repository at this point in the history
  • Loading branch information
fidothe committed Apr 8, 2011
1 parent 60bf4cd commit 213e345
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 2 deletions.
51 changes: 51 additions & 0 deletions README.md
@@ -0,0 +1,51 @@
CDN asset URL helpers
=====================

This library contains a Rubygem and Django custom templatetag library to do the following:

turn an asset path like

/images/thing.png

into a CDN-pointed URL like

http://cdn.name.com/images/thing.png/{sha1}.png

Rails
-----

Add `cdn_helpers` to your `Gemfile`:

gem 'cdn_helpers', :git => 'git@github.com:alphagov/cdn_helpers.git'

In your `environments/production.rb`:

require 'cdn_helpers'
config.action_controller.asset_host = "http://cdn.url.gov.uk"
config.action_controller.asset_path = CdnHelpers::AssetPath

Django
------

Add `cdn_helpers` to your `requirements.txt`:

-e git+ssh://git@github.com/alphagov/cdn_helpers.git#egg=cdn_helpers

in `settings.py` add cdn_helpers to your list of installed apps:

INSTALLED_APPS = (
'django.contrib.auth',
...
'cdn_helpers'
)

in the appropriate `local_settings.py`:

APP_DEPLOYMENT_ENV = 'dev' # (or staging, production)
CDN_HOSTS = ['cdn1', 'cdn2'] # (as appropriate for the environment)


in templates use the `asset_url` helper:

<img src="{% asset_url "/images/thing.png" %}">
<img src="{% asset_url thing.image.src %}">
2 changes: 1 addition & 1 deletion cdn_helpers.gemspec
Expand Up @@ -15,7 +15,7 @@ Gem::Specification.new do |s|
s.rubyforge_project = "cdn_helpers"

s.files = Dir[
'lib/**/*',
'rb/**/*',
'README.md',
'Gemfile',
'Rakefile'
Expand Down
17 changes: 16 additions & 1 deletion rb/cdn_helpers.rb
@@ -1,3 +1,18 @@
require 'digest/sha1'
module CdnHelpers
# Your code goes here...
module AssetPath
def self.asset_cache
@@asset_cache ||= {}
end

def self.call(path)
unless asset_cache.has_key?(path)
file_path = Rails.root.join('public', path.sub(/^\//, '')).to_s
sha1 = Digest::SHA1.file(file_path).hexdigest
extension = File.extname(path)
return asset_cache[path] = path + "/#{sha1[0..7]}#{extension}"
end
asset_cache[path]
end
end
end

0 comments on commit 213e345

Please sign in to comment.