Charlie
Charlie

Reputation: 265

Setting up custom formats for respond_to and respond_with in Ruby on Rails 4

I'm getting a ActionView::MissingTemplate when trying to get a custom output to behave with respond_to/with like it behaves xml/json output.

I have a custom output format available on my object.

@item.to_custom

I've registered the format with a custom Mime::Type registered in the mime_types.rb.

Mime::Type.register "application/custom", :custom

I have it listed in my respond_to options in my controller

class ItemsController < ApplicationController
  respond_to :html, :xml, :custom

And then I have a respond_with method before the end of my show action.

def show
  @item = Item.find(params[:id])    
  respond_with(@item) 
end

When I access items/1234.xml I get the xml output. When I try to access items/1234.custom I get an error ActionView::MissingTemplate. I can fix it by adding the file app/views/show.custom.ruby with the contents:

@item.to_custom

Is there a way to get to_custom to work like to_xml or to_json in a respond_to/with setup? To just use the to_custom method without needing a template? Or will I have to use a view template that calls the method explicitly?

Upvotes: 1

Views: 1926

Answers (1)

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

You'll need to manually add a Renderer for your custom format if you want it to render without explicitly adding a view template.

The Rails built-in formats xml and json have renderers automatically added from within the Rails framework, which is why they work right out of the box and your custom format does not (source code).

Try adding this in an initializer or right below where you register your MIME type

# config/initializers/renderers.rb
ActionController::Renderers.add :foo do |object, options|
  self.content_type ||= Mime::FOO
  object.respond_to?(:to_foo) ? object.to_foo : object
end

NOTE: Don't use custom as your format name because it will conflict with a method in the respond_with internals.

There is an excellent blog post that explains building custom Renderers in depth here: http://beerlington.com/blog/2011/07/25/building-a-csv-renderer-in-rails-3/

Upvotes: 3

Related Questions