ruby-on-railsrubyjsongrape-apigrape-entity

Rails, Grape entity. Expose on condition


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???


Solution

  • 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