使用Jbuilder(或其他)实现Rails JSON API布局 [英] Rails JSON API layouts with Jbuilder (or other)

查看:99
本文介绍了使用Jbuilder(或其他)实现Rails JSON API布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails 3.2应用程序中,我正在使用 jbuilder 来呈现来自JSON api的响应.

In my rails 3.2 app, I'm using jbuilder to render responses from my JSON api.

我想为所有API响应提供一个通用的结构,并且布局可能是使我的视图保持干燥的可能解决方案.

I want to provide a common structure to all API responses, and a layout would be the likely solution to keep my views DRY.

ex:我希望每个回复都采用以下形式:

ex: I'd like every response to be of the following form :

{
  status: "ok|error|redirect",
  data:   { ... JSON specific to the current view ... },
  errors: [ ... ],
  notes:  [ ... ]
}

(其中 data 的值是视图提供的json结构,其他所有内容都来自布局)

(where the value for data is a json structure provided by the view, everything else is from the layout)

但是:我无法正确地将jbuilder布局屈服于视图.

However: I can't get the jbuilder layout yielding to the view correctly.

# in layout 
json.data yield

# in view
json.some "value"

导致:

{"data":"{\"some\":\"value\"}"}  # arg! my json has become a string

以另一种方式尝试:

# in layout 
yield

# in view
json.data do |json|
  json.some "value"
end

结果:

{}

有人成功使用jbuilder或另一个json模板gem/method做到了吗?

Has anyone had success doing this with jbuilder, or another json templating gem/method?

juilder github问题表示有可能,但表明其他人也有类似问题.

This juilder github issue suggests it's possible, but indicates others are having similar issues.

我看到rabl(https://github.com/nesquena/rabl/)应该支持布局(https://github.com/nesquena/rabl/wiki/Using-Layouts),但是我已经决定不要出于其他原因使用它(rabl使复杂的json结构成为噩梦,特别是在尝试控制对象根目录时等).

I see rabl (https://github.com/nesquena/rabl/) is supposed to support layouts (https://github.com/nesquena/rabl/wiki/Using-Layouts), but I've decided not to use it for other reasons (rabl makes complex json structures a nightmare, particularly when trying to control object roots etc).

推荐答案

您可以通过这种方式完成

You can do this by this way

# api.v1.json.jbuilder - layout
json.request do
  json.message "your message"
  json.status 200
end
json.data JSON.parse(yield)

# show.json.jbuilder - action view
json.name 'Some item name'

这篇关于使用Jbuilder(或其他)实现Rails JSON API布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆