What is the correct way to check for objects in Rails / Ruby?

I have many models and relationships. Because of this, there are many calls in the views / controllers that look like this:

 @object.something.with_something.value 

Some part of the chain may turn out to be zero, which is quite normal. What is the correct / clean / quick way to check for the existence of a terminal object?

It calls something like:

 @object.something.with_something.value if defined? @object.something.with_something.value 

Is it considered ok?

+5
source share
4 answers

In the root you will need to use the &&(not defined?) operator , but it can be very verbose, very fast.

So instead:

(@object && @object.something && @object.something.with_something &&
  @object.something.with_something.value)

You can do this when ActiveSupport is present:

@object.try(:something).try(:with_something).try(:value)

:

Ick::Maybe.belongs_to YourClass
maybe(@object) { |obj| obj.something.with_something.value }
+8

, .

defined? , . - defined? nil .

:

@object.something.with_something.value if @object.something.with_something

:

nil.to_a => []
nil.to_s => ''
nil.to_f => 0.0
nil.to_i => 0

, , - nil Array, - , - :

something.to_a.each do |e|
  . . .
+3

what.you.are.doing " ". .

, , , -, "andand", , .

+2

Another option is to use the Null Object pattern to ensure that none of these objects will ever be zero. Perhaps if your code collects access this way, then something should always be defined.

0
source

All Articles