Custom Content-Type for File in Rails 'public' Folder
For assets stored in the 'public' folder of a ruby-on-rails application is it possible to change the 'Content-Type' when runni开发者_JS百科ng 'script/server'? For example, I am attempting to create an HTML5 application supporting offline mode, and have an 'offline.manifest'. When I run:
curl -I localhost:3000/offline.mainfest
The following header information is returned:
HTTP/1.1 200 OK
...
Content-Type: text/plain
...
However, HTML5 specifications require:
HTTP/1.1 200 OK
...
Content-Type: text/cache-manifest
...
As of Rails 5, putting this in an initializer works:
Rack::Mime::MIME_TYPES[".manifest"]="text/cache-manifest"
I'm not sure about other versions.
n.b. that it will not work to do Mime::Type.register "text/cache-manifest", :manifest
— this is only for rails controllers.
I'm not sure if Rails::Rack::Static
is used anywhere in Rails. Rails uses ActionDispatch::Static
, which doesn't inherit from Rails::Rack::Static
or anything like that. But it does use several things from Rack
, including Rack::Mime
, which is (i think?) completely separate from Mime
which is used elsewhere in Rails.
source for ActionDispatch::Static
: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/static.rb
Good question. I'd suggest digging into Rails::Rack::Static which is what serves files out of public these days.
Alternatively you could write a controller-action to serve just this filetype. Serve them up using send_file and pass the type explicitly eg:
send_file params[:filename], :type => 'text/cache-manifest'
http://apidock.com/rails/ActionController/Streaming/send_file
精彩评论