How To: Ruby+Passenger+Sinatra

Starting Off

Note:

Since I can’t put everything in the title, you need to know some things first before you try anything. If you’re going to be using ruby to make a website, or any kind of rails app, with Sinatra or otherwise, its best to go with whats called Passenger which attaches to your running webserver as a mod, for either Apache or nginx, or as a standalone server.

Some Pointers

Your best shot, in my own opinion would to also use a framework, or some could say ‘helper’ to make coding the website easier, the one I’ve found is Sinatra which has many of its own little helpers that can be used.

What you need

Folder Structure

Alright, now that you have them all set up, you need a good folder structure, this makes it easier to move around, and as you’ll see; let Sinatra and Passenger work well. Below is what the directory structure of scripts.electrocode.net looks like.


scripts/
├── botlist.json
├── bot.rb
├── common.motd
├── config.ru
├── def.rules
├── favicon.png
├── my_app.rb
├── public/
├── retrieve.rb
├── style.css
├── templates/
│   └── sass/
│       ├── index.sass
│       ├── layout.sass
│       └── uptime.sass
├── tmp/
│   └── always_restart.txt
└── views/
    ├── bot_form.erb
    ├── botlist.slim
    ├── ddate.slim
    ├── index.slim
    ├── layout.slim
    ├── motd.erb
    ├── retrieve.erb
    ├── rules.erb
    ├── uptime.slim
    └── view_info.slim

Made with tree

Making it Work

If you’re going to use Passenger and Sinatra together, you’re going to need 1(actually 2) starting file(s). config.ru


require './my_app'
run MyApp

my_app.rb


#! /usr/bin/ruby
#
require "sinatra/base"
require "tilt/erb"
require "tilt/slim"
require "tilt/sass"
require "tilt/haml"
require "json"
class SassHandler < Sinatra::Base
  set :views, File.dirname(__FILE__) + '/templates/sass'
  get '/css/*.css' do
    filename = params[:splat].first
    sass filename.to_sym
  end
end
class MyApp < Sinatra::Base
  set :protection, :except => :frame_options
  Slim::Engine.set_options pretty: true
  use SassHandler
  get "/" do
    table = JSON.load(File.open("table.json", "r"))
    slim :index, :locals => {"table" => table}
  end
end
# # start the server if ruby file executed directly
# run! if app_file == $0
# end

This is basically the skeleton that I started with, minus the SassHandler considering that’s how I’m getting css into the templates. Now in order to have some of these helpers, easily, you must have ‘gem’ available on your system. If you haven’t already, you will need to install Sinatra for any of this to work.

gem install sinatra sinatra-json

The json one lets you output json very easily with just Ruby code; More on that in a later post

gem install haml slim sass scss

After they are all installed, then you can start making your index.*

↑ Return to Top


  • If this page or post could use some sprucing up, let us know by contacting us through this link