2012-10-19 142 views
4

在露營中,如何最好地提供靜態文件,如css?如何提供靜態文件? (css)


現在我有

class Style < R '/cards.css' 
    def get 
     @headers["Content-Type"] = "text/css" 
     File.read('cards.css') 
    end 
end 

是否有涉及機架一個更聰明的方式?

回答

8

露營的電流(記得從安裝RubyGems的最新版本!)的靜態文件的立場是,服務器應負責提供靜態文件。

如果您使用camping命令,那麼應自動爲您提供public/目錄。只需將cards.csspublic/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 

我有不好的文檔道歉。現在你

+0

非常感謝你分享這個!我一直在挖掘這個答案很長一段時間。您從哪裏瞭解到「公共」目錄以及您在哪裏發現Camping會從該目錄提供靜態文件?在野營書中我找不到任何關於此的內容。 – IIllIIll

1

這裏有一個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,如上傳文件,會議等