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?
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.
inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With