Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nils and method chaining

I'm just breaking into the ruby world and I could use a helping hand.

Suppose b is nil.

I'd like the following code to return nil instead of a "NoMethodError: undefined method"

a.b.c("d").e

The first thing I tried was to overload NilClass's missing_method to simply return a nil. This is the behaviour I want except I don't want to be this intrusive.

I'd love it if I could do something like this

SafeNils.a.b.c("d").e

So it's like a clean way to locally overload the NilClass's behaviour.

I'd love to hear some ideas or great resources for digging in on this. I'm also quite open to other approaches as long as it's fairly clean.

Thank you very much.

like image 233
David Wright Avatar asked Aug 29 '11 20:08

David Wright


3 Answers

You can use the inline rescue:

x = a.b.c("d").e rescue nil

x will be nil if b is nil.

Or, as someone commented in that link, you can use the andand gem (see docs):

x = a.andand.b.andand.c("d").andand.e
like image 67
Sony Santos Avatar answered Sep 19 '22 17:09

Sony Santos


I think you can find a great solution in rails but that solution follows a different approach. Take a look at the try method. It's a clean approach.

like image 26
lucapette Avatar answered Sep 18 '22 17:09

lucapette


Starting from ruby v2.3.0 there is another way built into the language, the safe navigation operator (&.) You can write: a&.b&.c&.d and you will safely get nil if one of the calls in the chain returns nil. You can read more about it here: http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

like image 20
borod108 Avatar answered Sep 17 '22 17:09

borod108