How to serve static content from a controller in Rails?

2k views Asked by At

I'd like to serve static content from a controller action in Rails the same way that Rails serves static content out of the public directory. I do not want to just change the path of the public directory or add another path to Rails to serve files from there. I want to explicitly handle requests to specific files in a controller to verify the request depending on the requested files.

I naively tried to use send_file but then I can not use range requests anymore.

class MyController < ApplicationController
  def dummyAction
    filePath = 'foo/bar/baz.mp3'
    send_file(filePath, {:filename => "baz.mp3", :type => "audio/mpeg"})
  end
end

I'd prefer to use Rails instead of writing all the code myself. Is there something in Rails to do this? Maybe a Gem?

1

There are 1 answers

0
TrevTheDev On

Better to store your files in the assets directory or create a static resource controller or use public folder. See: http://railscasts.com/episodes/117-semi-static-pages and if you have access http://railscasts.com/episodes/117-semi-static-pages-revised this may of interest as well: https://github.com/thoughtbot/high_voltage

But if you must go this (wrong) way then: Add path to your config\routes.rb

resources :MyController do
 collection do
   get 'dummyAction'
 end
end

Add mime type to config/initializers/mime_types.rb:

Mime::Type.register_alias "audio/mp3", :mp3

Edit controller to:

def dummyAction
 respond_to do |format|
   format.mp3
 end
end

Save your file as MyController/dummyAction.mp3.erb