3 ms·
Because NilObject is actually an object, it is possible to add some methods that take some of the pain out of dealing with maybe-nil objects.. My favorite is t
by bhousel 17y ago
Because NilObject is actually an object, it is possible to add some methods that take some of the pain out of dealing with maybe-nil objects..
My favorite is the andand gem:
http://github.com/raganwald/andand/tree/master http://github.com/raganwald/andand/tree/master
It lets you turn code like this..
entry.at('description') && entry.at('description').inner_text
..into code like this..
entry.at('description').andand.inner_text
- masklinn 17y agoWhy not stick to EAFP and go with something along the lines of: begin entry.at('description').index_text rescue NoMethodError; end ?
- raganwald 17y agoWhat happens when you write: begin entry.at('description').indx_txt rescue NoMethodError end ? With the generic rescue you will always get nil back. With #andand you get nil from nil and a NoMethodError from objects, which is usually what you want. Also, if #index_text is correctly spelled but it raises a NoMethodError, you're silently discarding it again. For this reason, I avoid silently discarding exceptions even when I think I know what I'm doing. If I'm wrong, I'm in a lot of trouble...