Arun Agrawal’s Blog

Ruby on Rails Developer

Respond to Custom Formats in Rails

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 }
Now if you call this action with .mp3
You will redirect_to @mp3 url. Happy adding custom formats!!