【问题标题】:How to standardize JSON results of Rails projectRails项目的JSON结果如何标准化
【发布时间】:2015-03-25 03:12:23
【问题描述】:

我需要在 Rails 项目的 JSON 结果中添加额外的标签。

获取/菜单

{
  meta: {
    code: 200,
    message: ""
  }
  data: [
     // default rails response goes here
  ]
}

我不想在控制器中做这样的事情:

render json: { meta: { code: 200, message: ''}, data: @store.menus }

我查看了active_model_serializers gem,但没有找到任何提供此类自定义的选项。

【问题讨论】:

  • 你试过jbuilder了吗?根据我的经验,它使构建自定义 jquery 结构更容易github.com/rails/jbuilder
  • 额外标签是什么意思?注释?不支持评论。如果您正在谈论添加新字段,并且您正在使用 JSON 序列化哈希,只需在让 JSON 拥有它之前向哈希添加一个新的键/值。
  • 这个多余的标签没用,我只需要添加它们。别问我为什么!所以,我正在寻找一种奇特的方式来处理这个问题!
  • RE:“不清楚你在问什么”接近投票 - 这对我来说似乎很清楚。 OP 希望标准化 JSON 响应的结构,以便干掉控制器。

标签: ruby-on-rails ruby json active-model-serializers


【解决方案1】:

您可以创建一个JsonResponse 类来充当视图模型来包装您要发回的数据:

class JsonResponse
  attr_accessor :status, :message, :data

  STATUS_SUCCESS = 200;
  STATUS_CREATED = 201;
  STATUS_NOT_FOUND = 404;

  def self.success(data, message = nil)
    self.new(STATUS_SUCCESS, message || "OK", data)
  end

  def self.created(data, message = nil)
    self.new(STATUS_CREATED, message || "CREATED", data)
  end

  def self.not_found(data = nil, message = nil)
    self.new(STATUS_NOT_FOUND, message || "NOT FOUND", data)
  end

  def initialize(status = 200, message = "", data = nil)
    @status = status
    @message = message
    @data = data
  end

  def to_hash
    {
      meta: {
        code: status,
        message: message || ""
      },
      data: data.is_a?(Hash) ? data : data.to_hash
    }
  end
end

这为您提供了几种使用方法:

# One-liners
render json: JsonResponse.new(JsonResponse::STATUS_SUCCESS, nil, @store.menus).to_hash
render json: JsonResponse.success(@store.menus).to_hash
render json: JsonResponse.created(@store).to_hash
render json: JsonResponse.not_found.to_hash

# Multi-liners
response = JsonResponse.new JsonResponse::STATUS_SUCCESS, nil, @store.menus
response = JsonResponse.success @store.menus
response = JsonResponse.created @store
response = JsonResponse.not_found

# Render the JSON view
render json: response.to_hash

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 2012-07-02
    • 1970-01-01
    • 2011-08-26
    • 2015-07-11
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多