如何检查 Sinatra 中是否存在模板

发布于 2024-08-08 15:52:33 字数 480 浏览 1 评论 0原文

在 Sinatra ruby​​ 框架中,我有这样的路线:

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

如果模板存在(例如,如果我点击 /portfolio/website,并且我有一个名为 /views 的模板,则效果很好) /website.haml),但如果我尝试没有模板的 URL,例如 example.com/portfolio/notemplate,则会收到以下错误:

Errno::ENOENT 位于 /portfolio/notemplate
没有这样的文件或目录 - /.../views/notemplate.haml

如何测试和捕获模板是否存在?我在 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

年华零落成诗 2024-08-15 15:52:33

不确定是否有 Sinatra 特定的方法来做到这一点,但你总是可以捕获 Errno::ENOENT 异常,如下所示:

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

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
燃情 2024-08-15 15:52:33

第一个答案不是一个好的答案,因为如果文件不存在,无论如何都会创建一个符号。而且由于符号不会被垃圾收集,因此很容易泄漏内存。想象一下对不存在的文件进行的 ddos​​ 攻击,这些文件总是创建符号。而是在此处使用此路由(取自我的项目路由 css 文件之一):

# 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文