her icon indicating copy to clipboard operation
her copied to clipboard

Association has a truthy value when it is nil

Open vbalazs opened this issue 10 years ago • 1 comments

When I have an association and I return with nil in my API then the Her association will has a truthy value but it's clearly nil. This caused problems when I tried to use this in a condition.

I created a failing spec, you can find it here as a patch (you get the idea): https://gist.github.com/vbalazs/87e6991347baff4d8907

so using an association in a condition gives a surprising result:

if subject
  fail # shouldn't reach this
else
  pass
end

As well as

subject
=> nil
subject.class
=> NilClass
subject ? 1 : 0
=> 1 # wut? :)

As a workaround, I called .nil? on it and use that way but I think it would be worth fixing it. I tried to look into it but I lost myself around the proxy objects :confused:

Tested against v0.7.3.

vbalazs avatar Jan 23 '15 18:01 vbalazs

It's truthy because the association proxy object is always present, and it's nil? because the proxy object relays all methods_missing to the actually associated object, which is nil. The purpose is to lazy-load associates, and when the associated object is present it works very well.

A short-term fix would be for Her to add an .associate? method that simply calls .associate.present?

In the longer term, and ideally in the context of a proper error-handling framework (#334), I think the lazy-loader should be renamed so that once the actual associate exists the proxy can be bypassed:

   def subject
      _subject_proxy.lazy_loaded || nil
   end

Meanwhile we have got into the habit of checking associate.present?

will-r avatar Aug 05 '15 08:08 will-r