Rails项目的JSON结果

Rails项目的JSON结果

我需要在rails项目的json结果中添加额外的标记。
获取/菜单

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

我不想在控制器里做这样的事情:
render json: { meta: { code: 200, message: ''}, data: @store.menus }

我查看了active_model_serializersgem,但是没有找到任何提供这种定制的选项。

最佳答案

您可以创建一个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

08-03 13:46