Fork me on GitHub

Archive for August, 2011

Using Sprockets without Rails

Wednesday, August 31st, 2011

I’ve started working this week on an example application for the next book I’m about to write and I wanted a simple way for my readers to easily run the app (it’s going to be a single HTML file with a ton of cool JavaScript going on in it). My first choice for running this app was to use the popular Ruby library, Rack. If you are unfamiliar with Rack, please check it out. It provides a simple interface for writing web applications. By writing a simple Ruby file readers can use their favorite Rack compatible web server to launch the application. Sounds simple, eh? That’s because it is.

With a simple Rack application written in a few lines of code I was able to start developing my example application. That’s when I realized I needed a good way to serve up all my CoffeeScript and Sass files. I was going to write a watchr script that did this, but I thought that was a bit heavy handed, and not very flexible, so I turned to Sprockets.

Sprockets recently gained a lot of attention because it is bundled in with Rails 3.1 to serve up an application’s assets. It’s a clever little library that will process your files using CoffeeScript, Sass, etc… and let you bundle them up in to a single asset by using a manifest. That was exactly what I wanted. After I spent the better part of an afternoon doing a bit of research and debugging here is the Rack configuration file I came up with:

require 'sprockets'
project_root = File.expand_path(File.dirname(__FILE__))
assets = Sprockets::Environment.new(project_root) do |env|
  env.logger = Logger.new(STDOUT)
end

assets.append_path(File.join(project_root, 'app', 'assets'))
assets.append_path(File.join(project_root, 'app', 'assets', 'javascripts'))
assets.append_path(File.join(project_root, 'app', 'assets', 'stylesheets'))

map "/assets" do
  run assets
end

map "/" do
  run lambda { |env|
    [
      200,
      {
        'Content-Type' => 'text/html',
        'Cache-Control' => 'public, max-age=86400'
      },
      File.open('public/index.html', File::RDONLY)
    ]
  }
end
view raw config.ru This Gist brought to you by GitHub.

That will serve

/assets/application.css

via Sprockets. The file itself will live in

<pwd>/app/assets/stylesheets/application.scss

The same goes for JavaScript files.

Hopefully this will save someone else a little of time when they’re trying to do the same thing. Enjoy!

CoffeeScript – A Rubyist’s Love Affair

Wednesday, August 10th, 2011

Last night I had the pleasure of presenting to the Boston Ruby User’s Group on CoffeeScript. My talk was geared to helping Rubyists understand, and hopefully love, CoffeeScript. Along the way I tried to debunk a few myths and preconceptions as to what CoffeeScript is and isn’t. The reaction was really positive, so hopefully I did my job. Anyway, here are the slides:

http://www.slideshare.net/markykang/coffeescript-bostonrb-892011

 

Enjoy!