Adding a Time Stamp to preprocessed stylesheets

March 7, 2014 - By

A couple weeks ago I started hunting the Internet for a way to add a timestamp to my Sass compiled CSS. I’m currently collaborating with a lot of other front end devs on a very large project. The bottleneck happens in the CMS – there’s no way to run a local copy; so we often have to push out our CSS into the actual CMS dev site. Collisions are too easy, and it’s valuable to know how fresh the styles are, and who did them.

My Googling failed, but my colleague and desk-neighbour Tim Ziegel came to the rescue! Here’s his email: I wrote a quick ruby thingy to append banners to our SASS stylesheets with the compilation date/time and author.

Technically this hooks into compass, but regardless – any projects we set up that use a config.rb file to compile SASS with the compass dependency installed can use this.

The output looks like this at the top of each stylesheet:

/*--------------------------------------------------
Compiled on February 24, 2014 at 11:15am by tziegel
--------------------------------------------------*/

That’s it! No more changing the time manually when copying/pasting into RedDot. Super easy way to make sure we’re all on the same page.

Note that this only affects the flattened CSS files, the SCSS files remain the same.

All you have to do is paste the following into your config.rb file (should be in the root of your project). Oh, and change the author to whatever you want to be called.

author = 'tziegel'

on_stylesheet_saved do |oldfile|
	tempfile = oldfile + '.temp'
	divider = '--------------------------------------------------'
	File.open(tempfile, 'w') do |newfile|
		newfile.puts '/*' + divider
		newfile.puts 'Compiled on ' + DateTime.now.strftime("%B %d, %Y at %H:%M%P") + ' by ' + author
		newfile.puts divider + '*/'
		newfile.puts ' '
		File.foreach(oldfile) do |line|
			newfile.puts line
		end
	end
	File.rename(tempfile, oldfile)
end

 Cheers.

If you’re doing a WordPress site you’ll want to have the timestamp below your styles (style.css needs to start with the WP docblock). Simply rearrange the newfile bits like so:

 

author = 'Arleykins'

on_stylesheet_saved do |oldfile|
	tempfile = oldfile + '.temp'
	divider = '--------------------------------------------------'
	File.open(tempfile, 'w') do |newfile|
		File.foreach(oldfile) do |line|
			newfile.puts line
		end
		newfile.puts ' '
		newfile.puts '/*' + divider
		newfile.puts 'Compiled on ' + DateTime.now.strftime("%B %d, %Y at %H:%M%P") + ' by ' + author
		newfile.puts divider + '*/'
	end
	File.rename(tempfile, oldfile)
end

We’re still experimenting with this a bit. Some compilers (like Fire.app) seem to add the timestamp multiple times if you have the parent scss open. In source control we also needed to ignore the compiled files to avoid conflicts (they should have been ignored before I suppose, but they didn’t raise as much of a fuss).

Categorized in:

This post was written by ArleyM