views:

72

answers:

2

How do I serve a file statically with the correct content-type headers if it is not (for good reason) in the "public/" directory?

A: 

See Rack::Static.

module MyApp
  class Application < Rails::Application
    config.middleware.use Rack::Static,
      :urls => [ '/my-secret-dir' ],
      :root => 'my/secret/dir'
  end
end
Justice
What if I want to serve it dynamically?
Christoffer
Then use `send_file` as Gareth indicates.
Justice
+1  A: 

Rails has a send_file method which will do this

Gareth
Awesome, thank you!
Christoffer
Keep in mind that serving a static file by firing up a rails request works, but uses a lot of overhead.
fullware
Yes, this obviously runs everything through the Rails stack, so only do this if necessary - for example you need to base the download on dynamic authentication.
Gareth
Yes, I am aware of the overhead. But I cannot think of a better way to solve my problem. I'm building a small CMS with a file based template system, and each template can have it's own public directory, so which public directory to use is based on the template settings. I need the normal public-directory for the administration system.
Christoffer
Use XSendFile to avoid loading the Rails stack with the file transfers.
Vijay Dev
You can set up controller action which will catch routes into `/public /template/:id/:filename'. This action would only get called if the file doesn't exist as specified by the path, and it can then generate the file and place it there. Subsequent accesses will hit the asset directly. I personally use this for generating image thumbnails dynamically.
fullware