2012-02-22 60 views
11

到目前为止,我发现request.format.json?在Rails中是正确的(即传入请求被视为JSON)的两种方式。一种是如果您要求资源并以.json结尾,另一种是如果您在请求中提供标头Accept: application/json。每一项工作都是独立的。Rails:如何处理替代接受:内容类型为JSON?

我要注册自己的“接受”类型第二种情况:

Accept: application/vnd.myapp_v1+json,并通过这个导轨视为“JSON请求”像application/json,而不需要追加.json

我的第一个想法是注册我自己的MimeType为:json(在我的初始化代码中),但这实际上会中断对应用程序/ json的支持,而不是我想要做的。

Mime::Type.register "application/vnd.myapp_v1+json", :json # my failed attempt 

回答

8

我们到HTML移动iPhone请求在我们的应用程序具有的before_filter像这样:

before_filter :determine_format 

def determine_format 
    request.format = :iphone if (request.env["HTTP_USER_AGENT"] =~ /iPhone/ && request.format == :html) 
end 

我想你可以用你的特定格式类似的东西,也许是这样的:

def determine_format 
    request.format = :json if (request.format == 'application/vnd.myapp_v1+json') 
end 
+0

完美的作品!感谢您的回答。 – 2012-02-22 02:16:37

8

替代方案是:

api_mime_types = %W(
    application/vnd.api+json 
    text/x-json 
    application/json 
) 

Mime::Type.unregister :json 
Mime::Type.register 'application/json', :json, api_mime_types 

initializers/mime_types.rb