如何检查 Sinatra 中是否存在模板
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定是否有 Sinatra 特定的方法来做到这一点,但你总是可以捕获 Errno::ENOENT 异常,如下所示:
Not sure if there is a Sinatra specific way to do it, but you could always catch the Errno::ENOENT exception, like so:
第一个答案不是一个好的答案,因为如果文件不存在,无论如何都会创建一个符号。而且由于符号不会被垃圾收集,因此很容易泄漏内存。想象一下对不存在的文件进行的 ddos 攻击,这些文件总是创建符号。而是在此处使用此路由(取自我的项目路由 css 文件之一):
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):