Grape entities conditional expose if field is NOT nil
Asked Answered
C

2

7

In a grape-entity, I want to show a field only if present (not nil?) with no luck.

I'm trying this code but doesn't work as expected at all, but hiding the field always.

expose :winner, :using => PlayerEntity, :unless => { :winner => nil }

I think the code itself explains what I really need but, as I say, I'm not getting the expected result.

Any clue?

Crampon answered 22/2, 2014 at 6:22 Comment(0)
C
11

Ok, checking grape-entity's code I figured out you need to pass this block as a Ruby Proc. This code will work as expected:

expose :winner, :using => PlayerEntity, :unless => Proc.new {|g| g.winner.nil?}

Hope it helps someone. Cheers

Crampon answered 22/2, 2014 at 6:22 Comment(0)
P
3

https://github.com/ruby-grape/grape-entity#expose-nil

Grape Entity now provides expose_nil option, so this should do the trick:

expose :winner, :using => PlayerEntity, expose_nil: false
Pistol answered 5/3, 2019 at 8:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.