1

ぶどうエンティティを作成しました:

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

:healthcurrent:typeが に等しいかどうかを公開したいbasis。私はこの方法でそれにアクセスしようとします:

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

Health作成したjsonに属性が表示されません。私は使用できると思いますがexpose :health, if: :health、それも機能しません。私が間違っていることは何ですか?

4

1 に答える 1

3

You are slightly misunderstanding what :type does within Grape::Entity. It does not refer to the class that is being exposed, but an option that you pass on the call to present. It is probably not suitable for your purpose, unless you always know the class of objects you are sending to present (I am guessing that may not always be the case and you have some polymorphism here).

I think you just want this:

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

Grape::Entity will try a property and fail gracefully if it is not available or raises an error.

If other classes that you want to use do have the health property, but you want to hide those values, you can use the block form of 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

Or you can pass a Ruby Proc as the condition:

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

This last one may be better if you don't want to show existing health property at all for classes which have it other than Basis

于 2015-03-26T06:35:11.437 に答える