Monday, September 24, 2007

My Love of Haml, Sass, and Standalone Sass

I love using Haml in all of my Rails apps; it makes writing templates much easier and feels more elegant to me, even though the code may be a unusual at first:
.content_box
%h1= link_to(@page_title,show_url(@audio.show))
= render :partial => 'display', :locals => { :audio => @audio }
= graphic_link(@audio.show,'show_default')
But half the joy of Haml comes from using its excellent stylesheet engine, Sass. Sass adds a powerful abstraction layer on top of CSS, letting you use constant variables and simple expressions, and handling a lot of nested selector drudgery. It really feels like magic to use:
.storyteller_summary
:width 300px
:margin= 0 !one_gutter 0.25em 0
:float left
:clear left

.storyteller_photo
:float left

a
img.photo
:float left
:margin= 0 !half_gutter !half_gutter 0

becomes

.storyteller_summary {
width: 300px;
margin: 0 10px 0.25em 0;
float: left;
clear: left; }
.storyteller_summary .storyteller_photo {
float: left; }
.storyteller_summary .storyteller_photo a img.photo {
float: left;
margin: 0 5px 5px 0; }
.storyteller_summary p {
margin: 0 10px 0.25em 0px; }
.storyteller_summary p .block_description {
display: block;
margin: 0;
padding: 0; }
.storyteller_summary p .inline_description {
display: inline; }
.storyteller_summary p a.audio_icon img {
display: inline;
float: none;
margin: 0;
padding: 0; }
.storyteller_summary p strong {
margin: 0; }
Which is a beautiful thing. Recently I hired an excellent designer from elance.com to redesign this blog; while I can't say I executed her design perfectly, I got pretty close, and it really helped to use Sass in standalone mode. I had been using it exclusively as a Rails plugin, but as a gem it performs great as well. I wrote this little helper script to handle the transformation:
#!/usr/local/bin/ruby
require 'rubygems'
gem 'haml'
require 'sass'

template = IO.read('subelsky.sass')
open('subelsky.css','w+') { |file| file.write(Sass::Engine.new(template).render) }

3 comments:

Jarrod said...

figured out any easy way to have your stand alone sass run automatically (like say everytime you save your .sass file?)

Squeegy said...

rstakeout works great for this. It watches for filesystem updates and then runs a command.

http://nubyonrails.com/articles/automation-with-rstakeout

I stuck the above sassification code in a sassify.rb, and started rstakeout with:

rstakeout "./sassify.rb" stylesheets/sass/application.sass

Now everytime stylesheets/sass/application.sass gets saved, the sassify.rb gets run. Easy as pie.

Anonymous said...

Forget rstakeout. Use compass!