grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

Subclasses keep the parent's .documentation?

Open liclac opened this issue 10 years ago • 4 comments

I'm not sure if I'm using it wrong, or if it's bugged, but if I do this:

# api/entities/my_entity.rb
module API
  module Entities
    class MyEntity < Grape::Entity
      expose :name, documentation: { type: String, required: true }
      expose :message, documentation: { type: String }

      expose :created_at, documentation: { type: DateTime, required: true }
      expose :updated_at, documentation: { type: DateTime, required: true }

      expose :relation, using: API::Entities::Other, documentation: { is_array: true }

      def self.entity_name() "MyEntity" end

      class Update < API::Entities::MyEntity
        unexpose :created_at
        unexpose :updated_at
        unexpose :relation
      end
    end
  end
end

# api/entities/other.rb
module API
  module Entities
    class Other < Grape::Entity
      expose :created_at, documentation: { type: DateTime, required: true }
      expose :updated_at, documentation: { type: DateTime, required: true }
    end
  end
end

The results aren't quite what you'd expect in regards to .documentation:

$ rails console
Loading development environment (Rails 4.2.1)
irb(main):001:0> API::Entities::MyEntity.documentation
=> {:name=>{:type=>String, :required=>true}, :message=>{:type=>String}, :created_at=>{:type=>DateTime, :required=>true}, :updated_at=>{:type=>DateTime, :required=>true}, :relation=>{:is_array=>true}}
irb(main):002:0> API::Entities::MyEntity::Update.documentation
=> {:name=>{:type=>String, :required=>true}, :message=>{:type=>String}, :created_at=>{:type=>DateTime, :required=>true}, :updated_at=>{:type=>DateTime, :required=>true}, :relation=>{:is_array=>true}}

As a result, it currently appears to be impossible to use Entities for parameter reuse, without resorting to copypasting expose … lines into a separate class - making unexpose rather useless.

As a side note, it doesn't appear to be unexpose itself that's broken, as expose in a subclass similarly has no effect.

liclac avatar Apr 10 '15 12:04 liclac

Can you please describe what result are you expected from the above setup?

dan-corneanu avatar Apr 11 '15 04:04 dan-corneanu

I would expect unexpose'd attributes in the subclass to be absent from the subclass' documentation, and vice versa for newly expose'd.

liclac avatar Apr 11 '15 09:04 liclac

Yes, this is what I would expect too. I think this is a bug, the problem is most probably in the implementation of Grape::Entity#documentation which calls #documentation for the superclass too and merges with the subclass' documentation.

Can someone more knowledgeable confirm that this is indeed a bug? I would be more than happy to add a failing test and a fix for it.

dan-corneanu avatar Apr 11 '15 09:04 dan-corneanu

Yes, looks like a bug to me.

dblock avatar Apr 11 '15 16:04 dblock