Created
September 2, 2011 20:18
-
-
Save mrowl/1189785 to your computer and use it in GitHub Desktop.
Generating Tornado style static urls in Sass
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'digest/md5' | |
module Sass::Script::Functions | |
# Returns a url for static media (e.g. an icon) consistent with those | |
# generated by the static_url method in Tornado templates. The method | |
# takes an md5 hash of the given file and attaches the first five chars to | |
# the 'v' GET param in the url (i.e. it appends "?v=<hash_slice>"). | |
# Assumes you use a somewhat conventional Tornado layout: | |
# myapp/myapp - your code | |
# myapp/static - your static media | |
# myapp/sass - your base sass dir (probably has config.rb file) | |
# myapp/sass/sass - your scss dir | |
# Modify the http_path and local_path vars as needed | |
# Example SCSS: | |
# .icon { | |
# background: transparent url(static_url("img/my_awesome_icon.png")) no-repeat; | |
# } | |
# | |
# Generated CSS (the ?v=xxxxx hash will be different for your file obviously): | |
# .icon { | |
# background: transparent url("/static/img/my_awesome_icon.png?v=65309") no-repeat; | |
# } | |
def static_url(path_relative) | |
assert_type path_relative, :String | |
path_relative = unquote(path_relative) # Remove the quotes that Sass adds | |
http_path = "/static/#{path_relative}" # URL of the media file | |
local_path = "../static/#{path_relative}" # Path relative to Sass | |
# Make the 5 char hash a la Tornado | |
hash = Digest::MD5.hexdigest(IO.read(local_path))[0..4] | |
# Form the new url and return | |
Sass::Script::String.new("#{http_path}?v=#{hash}") | |
end | |
declare :static_url, :args => [:path_relative] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment