Rails,Grape实体。有条件的暴露

时间:2015-03-26 05:40:27

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

我创造了葡萄实体:

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

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

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

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

1 个答案:

答案 0 :(得分:2)

您对: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

如果您不想为除health

之外的其他类的类显示现有的Basis属性,那么最后一个可能会更好