Simplify multiple nil checking in Rails

后端 未结 10 1982
一个人的身影
一个人的身影 2020-12-17 06:44

How should I write:

if @parent.child.grand_child.attribute.present?
  do_something

without cumbersome nil checkings to avoid exception:

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 07:30

    For fun, you could use a fold:

    [:child, :grandchild, :attribute].reduce(@parent){|mem,x| mem = mem.nil? ? mem : mem.send(x) } 
    

    but using andand is probably better, or ick, which I like a lot and has methods like try and maybe.

提交回复
热议问题