Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grape entities conditional expose if field is NOT nil

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?

like image 567
Jorge Diaz Avatar asked Feb 22 '14 06:02

Jorge Diaz


2 Answers

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

like image 119
Jorge Diaz Avatar answered Nov 15 '22 13:11

Jorge Diaz


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
like image 3
lulalala Avatar answered Nov 15 '22 12:11

lulalala