Stasis with Compass and Sprockets

allard edited this page Jun 13, 2012 · 3 revisions
Clone this wiki locally

This is definitely a bit of a hack, so feel free to refine this with something smoother and prettier, and it works for me.

This outlines how to use stasis with Sprockets and Compass with the following features:

  • When completed you will have one compressed javascript and stylesheet file each with a unique filename
  • Only compile and compress style and javascripts when there's changes (takes an annoying long time otherwise)
  • Use git version as a unique filename generator so that we can have a long timeout for style and javascripts

in controller.rb:

layout 'layout.html.erb'
root = Dir.pwd

before 'index.html.erb' do
  %x{
    [[ ! -d #{root}/.sprocket-cache ]] &&             mkdir #{root}/.sprocket-cache
    [[ ! -d #{root}/.sprocket-cache/javascripts ]] && mkdir #{root}/.sprocket-cache/javascripts
    [[ ! -d #{root}/.sprocket-cache/stylesheets ]] && mkdir #{root}/.sprocket-cache/stylesheets
    [[ ! -d #{root}/.sprocket-cache/compiled ]] &&    mkdir #{root}/.sprocket-cache/compiled
  }

  if (%x{diff #{root}/stylesheets #{root}/.sprocket-cache/stylesheets >/dev/null; echo $?}.to_i.nonzero? || %x{diff #{root}/javascripts #{root}/.sprocket-cache/javascripts; echo $?}.to_i.nonzero?)
    puts %x{cd #{ root } &&
      compass compile &&
      sprocketize -cgj uglifier #{root}/.sprocket-cache/compiled/ .stylesheets-cache/stylesheet.css javascripts/javascript.js; echo 'sprocketize complete'
      rsync -a --delete #{root}/stylesheets/ #{root}/.sprocket-cache/stylesheets/
      rsync -a --delete #{root}/javascripts/ #{root}/.sprocket-cache/javascripts/
    }
  end
  %x{cd #{root}/.sprocket-cache/compiled; ls *}.split.each do |filename|
    new_filename = filename.gsub(/\.(css|js)(.*)/, "-#{git_version}." + '\1\2')
    %x{cp #{root}/.sprocket-cache/compiled/#{filename} #{root}/public/#{new_filename}}
  end

end

helpers do
  def git_version
    %x{git rev-parse HEAD}.strip
  end
end

in config.rb:

http_path = "/"
css_dir = ".stylesheets-cache"
sass_dir = "stylesheets"
images_dir = "images"
javascripts_dir = "javascripts"

in layout.html.erb:

<script src="/javascript-<%= git_version %>.js" type="text/javascript"></script>
<link href="/stylesheet-<%= git_version %>.css" media="screen" rel="stylesheet" type="text/css" />

Potential improvements if someone feels like it:

  • Not use that many hard coded dependencies.
  • Use the sprockets manifest file instead and write helper methods so that we could use unique filenames for images as well.
  • Detect development mode and expand the stylesheet and don't compress it (until we're ready to deploy)