3

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?

Jan Deinhard
  • 19,645
  • 24
  • 81
  • 137
  • Does this answer about 'accepting byte range requests through send_file' help? => http://stackoverflow.com/a/7604330/2463468 – benjaminjosephw Dec 11 '13 at 11:57
  • 1
    I was hoping for a more elegant solution. Rails seems to have facilities to serve static content. Range requests work when serving MP3 files out of the public directory. – Jan Deinhard Dec 11 '13 at 12:33

1 Answers1

-2

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

TrevTheDev
  • 2,616
  • 2
  • 18
  • 36