How to serve static files? (CSS)

In Camping, what is the best way to serve static files like css?


I have now

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

Is there a smarter way using Rack?

+4
source share
2 answers

The current camera (do not forget to install the latest version with RubyGems!), The position in static files is that the server should be responsible for maintaining static files.

If you use the camping command, then the public/ directory will be automatically sent to you. Just move cards.css to public/cards.css , and localhost: 3301 / cards.css should return the file.

During production, you must configure Apache / Nginx / whatever to work with files directly from the public/ directory.


If you cannot configure Apache / Nginx (for example, in Heroku), you can write your own config.ru as follows:

 # 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]) 

(This is what Camping :: Server does internally: https://github.com/camping/camping/blob/5201b49b753fe29dc3d2e96405d724bcaa7ad7d4/lib/camping/server.rb#L151 )


For small files, you can save them in the DATA block of your application .rb: https://github.com/camping/camping/blob/5201b49b753fe29dc3d2e96405d724bcaa7ad7d4/test/app_file.rb#L37

It is also useful if you want to save everything inside one file.

 Camping.goes :Foo __END__ @@ /cards.css ... 

Camping will use the file extension to set the correct content type.


Additionally, the latest version of Camping has a serve method that handles the Content-Type for you. You can simplify your controller:

 class Style < R '/style.css' def get serve "cards.css", File.read("cards.css") end end 

I will have to apologize for the poor documentation. At the moment you

+8
source

Here's a suggestion because of 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(@ __FILE__@ )) 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 . You can actually find other great ideas here , such as file downloads, sessions, etc.

+1
source

Source: https://habr.com/ru/post/1440881/


All Articles