ruby-grape / ruby-grape/grape-entity

expose_nil delegates to object, ignores methods defined in Entities

Open
#305 4 comments 9 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

expose_nil delegates to the underlying object and doesn't test whether the method is delegatable? This can lead to odd behaviour and errors.

You'd probably have to be doing inheritance with your Entities in order to encounter it in the wild, but as a contrived example:

class MyEntity < ::Grape::Entity
  expose :foo, expose_nil: false

  def foo
    'forty-foo'
  end
end

class FooableClass
  def initialize(foo = nil)
    @foo = foo
  end

  def foo
    @foo
  end
end

class NoFooFoYou
end

# In all 3 of the following, I'd argue that the expected result is {:foo=>'forty-foo'}

MyEntity.represent(FooableClass.new(42)).as_json
# => {:foo=>'forty-foo'}

MyEntity.represent(FooableClass.new).as_json
# => {}

MyEntity.represent(NoFooFoYou.new).as_json
NoMethodError: undefined method `foo' for #<NoFooFoYou:>

Would you agree this is an issue?

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 with lib/grape_entity/exposure.rb at the linked expose_nil delegation code, then inspect how delegatable? handles methods defined on Entity classes. Reproduce the three MyEntity examples from the issue and verify that inherited Entity methods are respected without calling missing methods on the represented object.

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.