ruby-grape / ruby-grape/grape-entity

Entity population fails with a relation named Klass

Open
#317 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
729
Forks
154
PR merge metrics
No merged PRs in 30d

Description

Bit of a unique use case here - we work in education, and thus have Student and Klass models and corresponding relationships. The call student.klass returns that student's "class" (meaning their classroom, not the programming class. I know - confusing). When nesting an entity inside of Student as detailed in the docs -

def entity
    Entity.new(self)
  end

  class Entity < Grape::Entity
    expose :name, :student_code
  end

and using present Student[:id] it fails with the error NoMethodError: undefined method 'ancestors' for #<Klass:0x007f9b734bbe30>. asdfa

Further digging led me to find that the entity_class_for_obj method inside lib/grape/dsl/inside_route.rb is to blame. More specifically, the condition at line #360 - object.respond_to?(:klass)

Technically, my class Student responds to this, but it returns an actual Klass object. This can be fixed by using with: Student::Entity but I would have to use that everywhere we return a student, which in our case would be a giant pain.

I was able to fix this by modifying the if statement to if object.respond_to?(:klass) && object.klass.class != Klass. I'm not sure if this is something that you'd want to add to the project since it is admittedly a pretty unique use case, but I'm not entirely sure why the check for .klass is there either. Nonetheless, any model that has a method 'klass' would presumably fail in this scenario. I couldn't see any unforeseen side effects other than having to deal with the added condition and associated object.klass.class != Klass word vomit...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib/grape/dsl/inside_route.rb at entity_class_for_obj, especially the object.respond_to?(:klass) condition, and trace why Student.klass is treated as an entity class. Reproduce the nested Student entity case with a model whose klass relation returns a Klass object. Done means entity population succeeds without requiring with: Student::Entity and existing entity-class detection still works.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.