What is the purpose of nil? and exists? methods in ruby/rails conditions? -


i (very often) see code in conditions:

<% catalog.each |article| %>   <% if article.image.nil? %>     ... 

or (e.g. seen there)

<% catalog.each |article| %>   <% if article.image.exists? %>     ... 

however know nil interprets false in conditions. activerecord query returns nil if nothing found.

why not write:

<% unless article.image %> (unless there article something)

instead of

<% if article.image.nil? %> (if there nothing @ article.image something)

and

<% if article.image %> instead of <% if article.image.exists? %>

i write code without nil? , exists?. missing? there pitfalls?

in example, , in many typical restful rails patterns, you're correct using implicit version identical in behavior.

but there suations nil? , exists? necessary and/or more readable...

for instance, nil? option when you're reading boolean attribute, , need different behavior false vs nil (since both falsey in ruby).

or, assume in example, each article has many images, , define method article's first image according display order:

def primary_image   images.order(display_order: "asc").limit(1) end 

in case, if article doesn't have images, primary_image return empty collection, truthy. so, in case, you'd need use exists? (or present?). rails provides several convenience methods checking data records.

(or make sure primary_image method returns nil or false when collection empty)


Comments