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

expose_nil delegates to object, ignores methods defined in Entities

Open al opened this issue 7 years ago • 4 comments

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?

al avatar Aug 10 '18 13:08 al

Just found today the same issue. I have a spec reproducing this behavior. Now I'm trying to do something to fix it 😄.

dsantosmerino avatar Aug 29 '18 15:08 dsantosmerino

Also encountered this and it seems someone has already fixed this in their fork :point_up:.

teoulas avatar Jan 25 '19 12:01 teoulas

Hi there, any news on that?

tscholz avatar May 11 '20 09:05 tscholz

I think this should be considered a bug. At least it's not mentioned in the README.

Thanks for grape-entity! :)

dchandekstark avatar Apr 20 '22 13:04 dchandekstark