views:

259

answers:

2

In the Sinatra ruby framework, I have a route like this:

get '/portfolio/:item' do
  haml params[:item].to_sym
end

This works great if the template that exists (e.g., if I hit /portfolio/website, and I have a template called /views/website.haml), but if I try a URL that doesn't have a template, like example.com/portfolio/notemplate, I get this error:

Errno::ENOENT at /portfolio/notemplate
No such file or directory - /.../views/notemplate.haml

How can I test and catch whether the template exists? I can't find an "if template exists" method in the Sinatra documentation.

+2  A: 

Not sure if there is a Sinatra specific way to do it, but you could always catch the Errno::ENOENT exception, like so:

get '/portfolio/:item' do
  begin
    haml params[:item].to_sym
  rescue Errno::ENOENT
    haml :default
  end 
end
ry
A: 

In theory that's what I'm trying to do, but it gives me the error

app.rb:47: syntax error, unexpected tSYMBEG, expecting kDO or '{' or '('
  rescue Errno:ENOENT
               ^

But I was able to get it working with

haml params[:item].to_sym rescue pass

Thanks for idea.

Eric Wright
You need to ":". `rescue Errno::ENOENT`
Damien MATHIEU
And the rescue pass doesn't allows you to display an other page. It justs ignores the thing (and ignoring errors is never a good idea).
Damien MATHIEU
dmathieu caught my typo. I've updated the code snippet above. I would be specific about which exception I was catching, since you might mask other sorts of errors with a blanket rescue.
ry
Good points. With the typo fix, ry's solution is the better way to handle it. Thanks.
Eric Wright