Sinatra, Mustache and Heroku

I’ve been playing around with Sinatra, in order to see how it would do in the wild I decided to use Heroku as a comfortable hosting solution.

Heroku

Begin creating your Sinatra app. Add a Gemfile, since Heroku runs a bundle install.

Commit to git.

To deploy to heroku install the heroku gem and create an instance for your app by calling “heroku create”. By default, this is enough to get going if you want the application to be run under a subdomain (e.g. http://codebrigade.heroku.com) you can do so by adding the desired name to the create.

If you push your app to &quote;heroku master&quote; it should boot and be running. If it doesn’t look into the log-files by typing &quote;heroku logs&quote; in your Command line.

Mustache

Mustache is a logic-less templating language derived from c-templates. Adding it to Sinatra is quite simple, install the mustache gem and add to your app.rb

require 'mustache/sinatra'
set :public => './public/'
register Mustache::Sinatra
require_relative 'views/layout'
set :mustache, {:views => './views/', :templates => './templates/'}

&quote;public&quote; holds static files like css. It works without explicitly setting it on my local machine but won’t do with Heroku, adding this fixes it.

It is important to include and provide the layout file since the engine looks for it.
The layout file includes the frame for all the views. For example:


<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
<link rel="stylesheet" type="text/css" href="layout.css">
</head>
<body>
<div id="header">{{> _header}}</div>
<div id="main">{{{yield}}}</div>
<div id="footer">{{> _footer}}</div>
</body>
</html>

My layout shows a custom Title for each view, header and footer are partials.
You will need a view and a layout for every page. All views extend the layout if they use it:

class Codebrigade
  module Views
    class Index < Layout
       def title
           "Hello there"
       end
    end
  end
end

Next steps are CouchDB and Sinatra integration…

Advertisements