Eric Wright
Eric Wright

Reputation: 815

How to check if a template exists in Sinatra

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.

Upvotes: 4

Views: 1912

Answers (2)

three
three

Reputation: 8478

The first answer is not a good one because if a file does not exist a symbol is created anyway. And since symbols are not garbage collected you're easily leaking memory. Just think of a ddos attack against nonexisitng files that create symbols all the time. Instead use this route here (taken from one of my projects routing css files):

# sass style sheet generation
get '/css/:file.css' do
  halt 404 unless File.exist?("views/#{params[:file]}.scss")
  time = File.stat("views/#{params[:file]}.scss").ctime
  last_modified(time)
  scss params[:file].intern
end

Upvotes: 5

ry.
ry.

Reputation: 8055

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

Upvotes: 5

Related Questions