Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to check for existence of objects in Rails / Ruby?

I have a lot of models and relations. Due to this fact, there is lot of calls in views/controllers, which look like this:

 @object.something.with_something.value 

Some part of the chain can end up being nil, which is perfectly ok. What is the proper/clean/fast way to check for the existence of the terminal object?

Is calling something like:

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

Considered ok?

like image 792
mdrozdziel Avatar asked Jan 19 '11 21:01

mdrozdziel


People also ask

What does .save do in Ruby?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.

What does :+ mean in Ruby?

inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.


1 Answers

Natively, you'd need to use the && operator (not defined?), but this can get very verbose, very quickly.

So instead of doing this:

(@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)

Or install the invocation construction kit and use its guarded evaluation tools:

Ick::Maybe.belongs_to YourClass
maybe(@object) { |obj| obj.something.with_something.value }
like image 85
Bob Aman Avatar answered Nov 15 '22 02:11

Bob Aman