在露营中,如何最好地提供静态文件,如css?如何提供静态文件? (css)
现在我有
class Style < R '/cards.css'
def get
@headers["Content-Type"] = "text/css"
File.read('cards.css')
end
end
是否有涉及机架一个更聪明的方式?
在露营中,如何最好地提供静态文件,如css?如何提供静态文件? (css)
现在我有
class Style < R '/cards.css'
def get
@headers["Content-Type"] = "text/css"
File.read('cards.css')
end
end
是否有涉及机架一个更聪明的方式?
露营的电流(记得从安装RubyGems的最新版本!)的静态文件的立场是,服务器应负责提供静态文件。
如果您使用camping
命令,那么应自动为您提供public/
目录。只需将cards.css
到public/cards.css
和本地主机:3301/cards.css应该返回文件。
在生产中,您应该配置Apache/Nginx /任何直接从public/
目录提供文件。
如果您不能配置Apache/Nginx的(例如,在Heroku的),你可以写一个自定义config.ru这样的:
# Your Camping app:
app = MyApp
# Static files:
files = Rack::File.new('public')
# First try the static files, then "fallback" to the app
run Rack::Cascade.new([files, app], [405, 404, 403])
(这就是露营:: Server内部的作用: https://github.com/camping/camping/blob/5201b49b753fe29dc3d2e96405d724bcaa7ad7d4/lib/camping/server.rb#L151)
对于小文件,你可以将它们存储在您的app.rb的数据块:https://github.com/camping/camping/blob/5201b49b753fe29dc3d2e96405d724bcaa7ad7d4/test/app_file.rb#L37
如果要将所有内容保存在一个文件中,这也很有用。
Camping.goes :Foo
__END__
@@ /cards.css
...
露营将使用文件扩展名来设置正确的Content-Type。
此外,Camping的最新版本有一个serve
-方法来处理您的内容类型。你完全可以简化您的控制器这样的:
class Style < R '/style.css'
def get
serve "cards.css", File.read("cards.css")
end
end
我有不好的文档道歉。现在你
这里有一个suggestion最初由whytheluckystiff:
class Static < R '/static/(.+)'
MIME_TYPES = {
'.html' => 'text/html',
'.css' => 'text/css',
'.js' => 'text/javascript',
'.jpg' => 'image/jpeg',
'.gif' => 'image/gif'
}
PATH = File.expand_path(File.dirname(@[email protected]))
def get(path)
@headers['Content-Type'] = MIME_TYPES[path[/\.\w+$/, 0]] || "text/plain"
unless path.include? ".." # prevent directory traversal attacks
@headers['X-Sendfile'] = "#{PATH}/static/#{path}"
else
@status = "403"
"403 - Invalid path"
end
end
end
PS - 其实,你可以找到其他一些伟大的想法here,如上传文件,会议等
非常感谢你分享这个!我一直在挖掘这个答案很长一段时间。您从哪里了解到“公共”目录以及您在哪里发现Camping会从该目录提供静态文件?在野营书中我找不到任何关于此的内容。 – IIllIIll