Respond to Custom Formats in Rails 4

Posted by arunagw on October 24, 2011

We usually respond some of the known formats in Rails Application like HTML, XML, JavaScript, RSS and some custom.

Have you tried to use your own custom format for your Rails Application?

Yes you can use your custom format in Rails Application.

Here showing a simple Rails Application with responding custom formats.

Get a new app

rails new music_library 

Get a scaffold into App

rails generate scaffold mp3 title:string url:string description:text 

Ok so you are ready to serve some music on your app with some formats!

Now you have to register MIME types in the Rails Application.

For that open up Rails.root/config/initializers/mime_types.rb

Mime::Type.register 'audio/mpeg' , :mp3

Now you can serve .mp3 and content

For that your respond block should look like

def show
  @mp3 = Mp3.find(params[:id])
  respond_to do |format|
    format.mp3 { redirect_to @mp3.url }
  end
end

Now if you call this action with .mp3

http://localhost:3000/mp3s/1.mp3

You will redirect_to @mp3 url.

Happy adding custom formats!!

Trackbacks

Use this link to trackback from your own site.

  • Miguel Michelsongs

    maybe you could use send_file to show the mp3 file directly in the same resource. The redirect part dont make sense.
    respond_to do |format|
    format.mp3 { send_file @mp3.url, :type => ‘audio/mpeg’, :disposition => ‘inline’ }end

    regards

    • http://agrawalarun.com Arun Agrawal

      Yes we can do this also!

  • Anonymous

    Nice! I like how you’ve created a simple example from scratch – makes it easy to try this myself :)

  • haripoter77

    Is there a way to render an MP3 file requested from a RoR server for a non-web app(Android app) ? I want to stream a music file in the server from the app.


Follow

Get every new post delivered to your Inbox

Join other followers