ruby-grape / grape-entity

An API focused facade that sits on top of an object model.
MIT License
721 stars 153 forks source link

expose_nil delegates to object, ignores methods defined in Entities #305

Open al opened 6 years ago

al commented 6 years ago

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?

dsantosmerino commented 6 years ago

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

teoulas commented 5 years ago

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

tscholz commented 4 years ago

Hi there, any news on that?

dchandekstark commented 2 years ago

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

Thanks for grape-entity! :)