Sinatra deserves an encore
I’m putting together a small site for a dancing troupe I’m involved with. Index page, bio pages, that’s about it. I want basic templating so I can keep my HTML dry. Initially I tried rolling my own solution with ERB and rake to generate HTML, but that was shit, so I found Sinatra and found that a much tastier. It’s kind of like camping but without all the weird meta-fu. Also, it has a sweet name and sweet copy:
1 2 3 4 |
$ ruby app.rb
== Sinatra has taken the stage on port 4567!
GET / | Status: 200 | Params: {:format=>"html"}
== Sinatra has ended his set (crowd applauds)
|
My app, sans views and data (use your imagination):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
['sinatra', 'yaml'].each {|x| require x } # This complex bit just loads up a YAML file and indexes an array of hashes # by their name. Also, it symbolizes keys because strings are for losers symbolize_keys = lambda {|a,v| a.update(v[0].intern => v[1]) } Data = YAML.load(File.open('data/performers.yml')).inject({}) {|a, v| a.update(v["name"].downcase => v.inject({}, &symbolize_keys))} layout do File.open('views/main.erb').read end helpers do def dancer data = Data[params[:id].downcase] data[:bio] = erb(:"dancers/#{params[:id]}") data end end get '/' do erb :index end get '/dancers/:id' do if dancer erb :dancer else status(404) end end static '/static', 'static' |
When I need to deploy to some cheap-cheap-we-support-nothing host I can just spider wget the whole site and FTP it up. For the complete integrated coding experience may I recommend Mr. Sinatra live with The Count Basie Band.
October 30, 2007 at 6:50 PM
Wonderful. You may shorten the layout with
layout ‘main.erb’
That will determine and read the file for you. This may change by the next version allowing you to use a symbol without the ext.
October 31, 2007 at 11:26 AM
I too have a love for Frank (we’re on a first name basis).
November 11, 2007 at 1:05 AM
Ohhh website for a dance troupe. What dance troupe could that be? Is this a secret? Should i know?
November 12, 2007 at 9:58 AM
‘Artful Dodgers’, one of Jodie’s things
November 12, 2007 at 10:18 AM
Also, if you use the layout ‘main.erb’ trick you don’t get a default layout and have to pass it in by hand for each action, which I don’t think is cool
November 12, 2007 at 6:24 PM
Correct. Sinatra looks for a erb/haml file named layout by default. There is no need to name something else unless you have multiple layouts.
i.e. views/layout.erb will work without explicitly declaring it as the layout.
February 01, 2008 at 11:56 PM
Thanks for sharing