在rails 3.2应用程序中,我使用jbuilder来呈现来自JSON的响应。
我希望为所有API响应提供一个公共结构,而布局将是保持视图干燥的可能解决方案。
例句:我希望每一个答复都是以下形式:
{
status: "ok|error|redirect",
data: { ... JSON specific to the current view ... },
errors: [ ... ],
notes: [ ... ]
}
(在data的值是视图提供的json结构的情况下,其他一切都来自布局)
但是:我无法正确地获得符合视图的jbuilder布局。
# 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模板创业板/方法中成功地做到了这一点?
这个juilder github问题表明这是可能的,但也表明其他人也有类似的问题。
我看到rabl (https://github.com/nesquena/rabl/)应该支持布局(https://github.com/nesquena/rabl/wiki/Using-Layouts),但出于其他原因,我决定不使用它(rabl使复杂的json结构成为噩梦,特别是在试图控制对象根等时)。
发布于 2012-09-24 12:25:44
你可以这样做
# 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'
发布于 2012-10-11 04:14:53
我将根据我们想出的解决方案给出一个备选方案:
# app/helpers/application_helper.rb
module ApplicationHelper
def envelope(json, status, errors, notes)
json.status status
json.data do
yield if block_given?
end
json.errors errors
json.notes notes
end
end
然后,在视图中,可以调用信封并包含json代码,如下所示:
# app/views/api/v1/test/show.json.jbuilder
envelope(json, "OK" ) do
json.some 'value'
end
发布于 2014-10-15 16:13:46
迟了回答,但帮我得到了我想要的.
成功结果:
{ "something": {"id": 42, "message": "hello"}, "status": "ok", "errors": [] }
错误结果:
{ "something": null, "status": "error", "errors": ["could not do the thing"] }
代码:
app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ActionController::API
layout 'api/v1/application'
before_action :setup_layout_elements
def setup_layout_elements
@status = :ok
@errors = []
end
def error!(message)
@status = :error
@errors << message
nil
end
end
app/controllers/api/v1/some_controller.rb
class Api::V1::SomeController < Api::V1::BaseController
def index
@something = begin
possibly_error_causing_code
rescue
error!('could not do the thing')
end
render builder: 'api/v1/something/index'
end
end
app/views/layouts/api/v1/application.json.jbuilder
json.merge! JSON.parse(yield)
json.status @status
json.errors @errors
app/views/api/v1/something/index.json.jbuilder
json.something do
json.id @something.id
json.message @something.to_s
end
https://stackoverflow.com/questions/11516616
复制相似问题