Tuesday, February 28, 2012

Sass Color Palette Generator


Inspired by EngineYard's Front-End Maintainability with Sass and Style Guides article about how helpful it is to keep track of your Sass color variables in one place I sought to automate the process a little bit. There are a bunch of ways that this could be done, but I took a really simple client-side approach. Just make sure your _scss file is publicly accessible and this code should generate an always-up-to-date style guide from your Sass (scss) color file. What do you think?




var $colors = $("#colors");
var url = "/css/sass/_colors.scss";
$.get(url, function(data) {
var lines = data.split("\n");
var line = "";
var parts = [];
for (var i = 0; i < lines.length; i++) {
line = lines[i].trim();
if (!line.match(/^\$/)) continue;
parts = line.split(/\:\s+/);
if (parts[1].match(/^#/) || parts[1].match(/^rgba?/)) {
addColor(parts[0], parts[1])
}
}
}, "text");
function addColor(name, color) {
var $li = $("<li>", {style: "background: " + color, text: name + " " + color.slice(0, -1)});
$colors.append($li);
}

Saturday, February 25, 2012

Express.js Dynamic Helpers vs. Middleware


If you're build a site in express.js that relies on variables being set on every single page you may be tempted to use middleware and for a long time I've done something like this. It works fine.

// app.js file
var middleware = require('./util/middleware')
app.use(middleware.setLocals)

// middleware.js file
exports.setLocals(req, res, next) {
  res.local("currentPageName", applyFancyFormatting(req.url))
  res.local("luckyNumber", Math.floor(Math.random() * 100))
  next()
}

Express has something called dynamicHelpers that were built specifically with this in mind. It's a little bit simpler and in my opinion cleaner. It also doesn't make you next() after each one. You can put this anywhere you'd put an app.use statement. Check it out:

app.dynamicHelpers({
    currentPageName: function(req, res) {
        return applyFancyFormatting(req.url)
    },
    luckyNumber: function() {
      return Math.floor(Math.random() * 100))
    }
})

Or you can be like me and store them in different files like this:

// app.js
var dynamicHelpers = require('./util/dynamicHelpers')
app.dynamicHelpers(dynamicHelpers)

// utils/dynamicHelpers.js file
exports.currentPageName = function(req, res) {
    return applyFancyFormatting(req.url);
}
exports.luckyNumber = function() {
   return Math.floor(Math.random() * 100);
}


See it's great isn't it? What do you think?