8
votes

Using ROAR ( https://github.com/apotonick/roar ) and without using ActiveRecord or any view-templates I want to:

  • use the default JSON rederer but my own mime type to render JSON with respond_with
  • use the default JSON parser but my own mime type to put entries of the POST-body into the params hash.

config/initializers/mime_types.rb:

Mime::Type.register "application/vnd.xxx-v1+json" , :xxx_v1

controllers/api/base_controller.rb

class Api::V1::BaseController < ActionController::Base
  respond_to :xxx_v1

  ActionController.add_renderer :xxx_v1 do |obj, options|
    json = obj.to_json
    self.content_type ||= Mime::Type.lookup('application/vnd.xxx-v1+json')
    self.response_body  = json
  end
end

controllers/api/user_controller.rb:

class Api::V1::UsersController < Api::V1::BaseController 

  def index
    respond_with User.all
  end
end

GET http://domain/users Accept application/vnd.xxx-v1

ERROR: Missing template api/v1/users/index, api/v1/base/index with {:handlers=>[:erb, :builder], :formats=>[:xxx_v1], :locale=>[:en, :en]}

After reading several posts like Rails Custom Renderer or rails 3 response format and versioning using vendor MIME type in the Accept header I still can't get it work..

-=== small update ===-

When I use render directly in the controller, it's working! Always problems with respond_with...

render :xxx_v1 => User.all
2

2 Answers

4
votes

For automatic parsing of http bodies with custom mime types do: config/initializers/mime_types.rb :

ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime::Type.lookup('application/vnd.xxx_v1+json')]=lambda do |body|
  JSON.parse(body)
end
3
votes

Solution for rendering:

Put an empty method into your models:

def to_xxx_v1
end

It is not called but has to be present for respond_with.