简体   繁体   English

上下文相关的JSON响应

[英]Context-Sensitive JSON Response

I am creating a rails 3 backend that consists of RESTful json controllers. 我正在创建一个由RESTful json控制器组成的Rails 3后端。 Eg the controllers look something like this: 例如,控制器看起来像这样:

respond_to :json

def index
  ...
  respond_with resources
end

...

This is consumed by jQuery on the client. 这由客户端上的jQuery使用。 Everything is working great. 一切都很好。

My next step is to control the JSON so that some properties are not serialized depending on the context. 我的下一步是控制JSON,以便根据上下文不对某些属性进行序列化。 Eg the owner of the resource gets more properties sent down than someone who only has read access. 例如,资源所有者比仅具有读访问权的人获得更多的属性下传。

I am currently tending towards Draper and using separate decorators for each model based on the user's role. 目前,我倾向于使用Draper,并根据用户的角色为每个模型使用单独的装饰器。

My problem is that this is generating a lot of boilerplate. 我的问题是,这会产生很多样板。 I am also currently using cancan for role based authorization. 我目前也在使用cancan进行基于角色的授权。

Can anyone suggest a better method for accomplishing this? 谁能建议一种更好的方法来实现这一目标?

I recommend using ActiveModel::Serializer. 我建议使用ActiveModel :: Serializer。 See https://github.com/josevalim/active_model_serializers 参见https://github.com/josevalim/active_model_serializers

Create a serializer for each resource you want to expose. 为要公开的每个资源创建一个序列化器。 You can then separate the serialization logic for each model, easily expose other methods, and scope each model based on roles. 然后,您可以为每个模型分离序列化逻辑,轻松地公开其他方法,并根据角色确定每个模型的范围。 It works well with CanCan. 与CanCan搭配使用效果很好。

I like this syntax, for example: 我喜欢这种语法,例如:

class MonkeySerializer < ActiveModel::Serializer
  attributes :name, :mom, :weight

  private

  # use this for a custom attribute not on the model
  def weight
    monkey.weight_in_pounds
  end    
end 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM