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
end

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

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

@@index
h1 @title

@@script
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