15

For a small developer documentation app, I'd like to set up a Sinatra app to just serve HAML files. After routes for CSS files and images, I want a route that tries to load a HAML file for any path you request.

For example:

  • /index loads views/index.haml, if it exists
  • /this/page/might/exist loads views/this/page/might/exist.haml, if it exists

How would I specify this route?

Nathan Long
  • 122,748
  • 97
  • 336
  • 451

1 Answers1

24

Looks like this will do it:

get '/*' do
  viewname = params[:splat].first   # eg "some/path/here"

  if File.exist?("views/#{viewname}.haml")
    haml :"#{viewname}"

  else
    "Nopers, I can't find it."
  end
end
Nathan Long
  • 122,748
  • 97
  • 336
  • 451
  • 1
    I had to put this 'after' all my other routes, to make sure they get processed, otherwise the catchall route `/*` would block all the other routes – Rots Sep 26 '13 at 21:33
  • @nroose - a 500 error is something a web server would return; it can't happen in Ruby. If, eg, the `haml` call raises an error, you're right that I wouldn't rescue it and my site would return a 500. Also, to be more correct, I should send a 404 status code in the header when sending the body "I can't find it". But this is just a simple example. – Nathan Long Apr 09 '14 at 14:28
  • Just wanted to note that this _does_ cover `/` (the root route) – Freedom_Ben Jan 18 '21 at 21:06