【问题标题】:Rails, Grape entity. Expose on conditionRails,葡萄实体。有条件暴露
【发布时间】:2015-03-26 05:40:26
【问题描述】:

我已经创建了葡萄实体:

class VehicleDetails < Grape::Entity
  expose :id
  expose :name
  expose :type
  expose :health, if: {type: 'basis'}
end

如果当前:type 等于basis,我想公开:health。我尝试通过这种方法访问它:

 get :details do
  present Basis.all, with: GameServer::Entities::VehicleDetails
 end

Health 属性未显示在我创建的 json 中。我想我可以使用expose :health, if: :health,它也不起作用。我做错了什么???

【问题讨论】:

    标签: ruby-on-rails ruby json grape-api grape-entity


    【解决方案1】:

    您对:typeGrape::Entity 中的作用略有误解。它不是指公开的类,而是您将调用传递给present 的选项。它可能不适合您的目的,除非您始终知道要发送到 present 的对象类别(我猜可能并非总是如此,并且您在这里有一些多态性)。

    我想你只是想要这个:

    class VehicleDetails < Grape::Entity
      expose :id
      expose :name
      expose :type
      expose :health
    end
    

    Grape::Entity 将尝试一个属性,如果它不可用或引发错误,则会优雅地失败。

    如果您想使用的其他类确实具有health 属性,但您想隐藏这些值,您可以使用expose 的块形式:

    class VehicleDetails < Grape::Entity
      expose :id
      expose :name
      expose :type
      expose( :health ) do |vehicle,opts| 
        vehicle.is_a?( Basis ) ? vehicle.health : nil
      end
    end
    

    或者你可以传递一个 Ruby Proc 作为条件:

    class VehicleDetails < Grape::Entity
      expose :id
      expose :name
      expose :type
      expose :health, :if => Proc.new {|vehicle| vehicle.is_a?( Basis )}
    end
    

    如果您根本不想为具有 Basis 以外的类显示现有的 health 属性,最后一个可能会更好

    【讨论】:

      猜你喜欢
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多