Sinatra templates from params

Having been playing about with Sinatra I’m finding it cropping up in all kinds of useful ways. I shouldn’t be too surprised though, as that is the whole raison d’etre of micro-frameworks.

When I get around to it I am writing a little Sinatra app, but for me it has a found a real niche helping to prototype or mess around with CSS and Javascript – it only takes a few seconds to create a little app to play around with.

Here is a minimal app.rb file. It will load templates from the (default) /views directory based on the :name parameter.

require 'rubygems'
require 'sinatra'

get '/' do
    erb :index

get '/map/:name' do
    erb params[:name].to_sym

The key here is to_sym – this is not Sinatra specific it is part of the Ruby language. to_sym converts a string into a symbol.

If the concept of a symbol is a little woolly read this for an excellent explanation. An easy (although probably incorrect or simplistic) is to think of a ruby symbol simply as an immutable name for something that can either be a string or an integer. Once created it cannot change.