I have created grape entity:
class VehicleDetails < Grape::Entity
expose :id
expose :name
expose :type
expose :health, if: {type: 'basis'}
end
I want to expose :health if current :type is equal to basis. I try to access it by this method:
get :details do
present Basis.all, with: GameServer::Entities::VehicleDetails
end
Health attribute does not shows in my created json. I thouht I could use expose :health, if: :health, it does not work too. What I am doing wrong???
You are slightly misunderstanding what
:typedoes withinGrape::Entity. It does not refer to the class that is being exposed, but an option that you pass on the call topresent. It is probably not suitable for your purpose, unless you always know the class of objects you are sending topresent(I am guessing that may not always be the case and you have some polymorphism here).I think you just want this:
Grape::Entitywill 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
healthproperty, but you want to hide those values, you can use the block form ofexpose:Or you can pass a Ruby
Procas the condition:This last one may be better if you don't want to show existing
healthproperty at all for classes which have it other thanBasis