CoffeeScript In Sinatra

CoffeeScript Logo

In case you haven’t heard, CoffeeScriptis an awesome little language that compiles into JavaScript. It basically makes JavaScript nice (and a lot more like Ruby).

Sinatra has an easy-to-use helper that allows you to write CoffeeScript in your views that is compiled to JavaScript on the server.

First you need to install some gems:

%> gem install coffee-script therubyracer

Now open up your text editor and we’ll create a little demo app all in one file:

require 'sinatra'
require 'slim'
require 'v8'

get '/application.js' do
  coffee :script

get '/' do
  @title = "CoffeeScript in Sinatra"
  slim :index

doctype html
    meta charset="utf-8"
    title @title
    script src="/application.js"
    == yield

h1 @title

alert 'Coffeescript is working.'

That’s how simple it is!

Sorry that the actual JavaScript I used was so trivial but I wasn’t feeling very inspired. I hope you find CoffeeScript as nice to use in your Sinatra apps as I have.

blog comments powered by Disqus