ruby-on-railsrubyactivesupport

Better alternative to try method


I would like a clean piece of code and I think this feels clunky.

Is there a better way to do this?

User.try(:profile).try(:settings).try(:card).try(:options)

If I eliminate the try methods, I get a nil method error.

Is there another piece of code that does something like:

User.try(:profile,:settings, :card, :options)

Solution

  • From ruby 2.3.0 you can use &. method instead of try:

    User&.profile&.settings&.card&.options
    

    But you should avoid things like this.

    When you send messages to objects that might return nil or when the object doesn't respond to that message, that's a problem you should solve on its own. Using try only exacerbates the problem, in the same way that nil-checking does. Write consistent interfaces that behave consistently.