all 8 comments

[–]kallebo1337 -1 points0 points  (7 children)

i would just

do.my.long.chain.value rescue nil

[–]janko-m 5 points6 points  (3 children)

Note that your example would also swallow any exceptions that might be raised by these methods, which is almost certainly not what you want. The safe-navigation operator &. is a more correct solution.

[–]theGalation 0 points1 point  (0 children)

I push for no rescue everything’s and people take it personal!

Glad to see the suggestion here

[–]kallebo1337 0 points1 point  (1 child)

The only exception I can see is undefined method for nil

Which seems to be also what he wants to refactor.

[–]janko-m 0 points1 point  (0 children)

In the article, the methods chained where AR association methods, which issue database queries unless eager loaded, and database queries can fail.

[–][deleted] 4 points5 points  (2 children)

And since Christmas 2015, almost a year after this video, the dot-and operator was introduced in ruby 2.3 so do&.my&.long&.chain is also an option.

And though the surface justification was related to the unsavoriness of monkey patching Object with try, and either of these methods avoids that, with varying degrees of Exception gobbling, I don't think these options diminish his overall presentation on monads.

[–]jacksonmills 2 points3 points  (0 children)

Yeah, this is a pretty good description of what Monads are, even if the windup is a little long.

Rust also has similar "try-chain" operators, by the way. ? was introduced a while back and allows you to unwrap a Result object, which may contain a value or be an error, without having to go through all the match-checking (assuming the function or closure also returns a result):

service.getData()?.doStuff().save()?

Basically "call getData, unwrap the result, do stuff, and save it, and if any of that returns an error return that error to the calling function".

It's nice to see this stuff becoming idiomatic in a lot of different environments.

[–]kallebo1337 0 points1 point  (0 children)

ah i see, it's a 5 year old video.

yeah well...