Better alternative to try methodHow to generate a random string in RubyHow to find where a method is defined at runtime?Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?How to set default values in Rails?Rails :include vs. :joinsGiven a class, see if instance has method (Ruby)How do I parse a YAML file?Disable Rails SQL logging in consoleWhat is the right way to override a setter method in Ruby on Rails?Deleting an instance of a class via a method of that class

Bash method for viewing beginning and end of file

Personal Teleportation as a Weapon

voltage of sounds of mp3files

How will losing mobility of one hand affect my career as a programmer?

Print name if parameter passed to function

Mapping a list into a phase plot

How could Frankenstein get the parts for his _second_ creature?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

What to do with wrong results in talks?

Irreducibility of a simple polynomial

Opposite of a diet

Why is delta-v is the most useful quantity for planning space travel?

Products and sum of cubes in Fibonacci

Tiptoe or tiphoof? Adjusting words to better fit fantasy races

Is it correct to write "is not focus on"?

Is exact Kanji stroke length important?

Can somebody explain Brexit in a few child-proof sentences?

Can criminal fraud exist without damages?

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

Why Were Madagascar and New Zealand Discovered So Late?

Increase performance creating Mandelbrot set in python

Why does John Bercow say “unlock” after reading out the results of a vote?

Coordinate position not precise

Finding all intervals that match predicate in vector



Better alternative to try method


How to generate a random string in RubyHow to find where a method is defined at runtime?Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?How to set default values in Rails?Rails :include vs. :joinsGiven a class, see if instance has method (Ruby)How do I parse a YAML file?Disable Rails SQL logging in consoleWhat is the right way to override a setter method in Ruby on Rails?Deleting an instance of a class via a method of that class













2















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)









share|improve this question
























  • BTW the reason why User.try(:profile,:settings, :card, :options) doesn't work is due to the fact that you can provide method parameters and blocks with try. The above code tries to do User.profile(:settings, :card, :options).

    – 3limin4t0r
    Mar 1 at 22:08















2















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)









share|improve this question
























  • BTW the reason why User.try(:profile,:settings, :card, :options) doesn't work is due to the fact that you can provide method parameters and blocks with try. The above code tries to do User.profile(:settings, :card, :options).

    – 3limin4t0r
    Mar 1 at 22:08













2












2








2








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)









share|improve this question
















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)






ruby-on-rails ruby activesupport






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 1 at 17:50









SRack

4,50941738




4,50941738










asked Mar 1 at 16:55









user2012677user2012677

1,52641640




1,52641640












  • BTW the reason why User.try(:profile,:settings, :card, :options) doesn't work is due to the fact that you can provide method parameters and blocks with try. The above code tries to do User.profile(:settings, :card, :options).

    – 3limin4t0r
    Mar 1 at 22:08

















  • BTW the reason why User.try(:profile,:settings, :card, :options) doesn't work is due to the fact that you can provide method parameters and blocks with try. The above code tries to do User.profile(:settings, :card, :options).

    – 3limin4t0r
    Mar 1 at 22:08
















BTW the reason why User.try(:profile,:settings, :card, :options) doesn't work is due to the fact that you can provide method parameters and blocks with try. The above code tries to do User.profile(:settings, :card, :options).

– 3limin4t0r
Mar 1 at 22:08





BTW the reason why User.try(:profile,:settings, :card, :options) doesn't work is due to the fact that you can provide method parameters and blocks with try. The above code tries to do User.profile(:settings, :card, :options).

– 3limin4t0r
Mar 1 at 22:08












4 Answers
4






active

oldest

votes


















5














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.






share|improve this answer























  • If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

    – Sebastian Palma
    Mar 1 at 18:05











  • @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

    – Зелёный
    Mar 1 at 18:14












  • As an aside try and safe navigation &. are not exactly equivalent Spec

    – engineersmnky
    Mar 1 at 20:13












  • ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

    – 3limin4t0r
    Mar 1 at 21:54


















3














If you are using a Ruby version greater than 2.3, you can use the safe operator instead. For example,



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


Isn't that neat?






share|improve this answer






























    3














    Just for fun



    Roll your own:



    # concerns/deep_try.rb

    module DeepTry
    def deep_try(*methods)
    methods.reduce(self) receiver.try(method)
    end
    end

    # user.rb (or anywhere else you want it)
    extend DeepTry


    That would let you safely call the following:



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


    You could also use on an instance level:



    @user.extend(DeepTry).deep_try(:profile, :settings, :card, :options)





    share|improve this answer

























    • tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

      – 3limin4t0r
      Mar 1 at 22:13












    • Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

      – SRack
      Mar 7 at 11:45


















    0














    I know this is out in left field, but you know, diversity in thinking.



    I have created the (very tiny) insouciant gem that allows code to be executed with worrying about errors. Using this gem the code would look like:



    insouciant(nil) User.profile.settings.card.options 


    with the slight added "benefit" of catching all standard errors, not just nil method errors. The nil value is returned on an error. You can replaced it with some other value if that makes more sense in your application.



    Omitting the parameter entirely will return the error message as a string.






    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54949112%2fbetter-alternative-to-try-method%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5














      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.






      share|improve this answer























      • If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

        – Sebastian Palma
        Mar 1 at 18:05











      • @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

        – Зелёный
        Mar 1 at 18:14












      • As an aside try and safe navigation &. are not exactly equivalent Spec

        – engineersmnky
        Mar 1 at 20:13












      • ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

        – 3limin4t0r
        Mar 1 at 21:54















      5














      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.






      share|improve this answer























      • If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

        – Sebastian Palma
        Mar 1 at 18:05











      • @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

        – Зелёный
        Mar 1 at 18:14












      • As an aside try and safe navigation &. are not exactly equivalent Spec

        – engineersmnky
        Mar 1 at 20:13












      • ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

        – 3limin4t0r
        Mar 1 at 21:54













      5












      5








      5







      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.






      share|improve this answer













      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.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 1 at 17:03









      ЗелёныйЗелёный

      30.2k75371




      30.2k75371












      • If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

        – Sebastian Palma
        Mar 1 at 18:05











      • @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

        – Зелёный
        Mar 1 at 18:14












      • As an aside try and safe navigation &. are not exactly equivalent Spec

        – engineersmnky
        Mar 1 at 20:13












      • ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

        – 3limin4t0r
        Mar 1 at 21:54

















      • If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

        – Sebastian Palma
        Mar 1 at 18:05











      • @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

        – Зелёный
        Mar 1 at 18:14












      • As an aside try and safe navigation &. are not exactly equivalent Spec

        – engineersmnky
        Mar 1 at 20:13












      • ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

        – 3limin4t0r
        Mar 1 at 21:54
















      If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

      – Sebastian Palma
      Mar 1 at 18:05





      If User is an uninitialized constant, it raises a NameError error, so, the safe navigation operator won't work as expected.

      – Sebastian Palma
      Mar 1 at 18:05













      @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

      – Зелёный
      Mar 1 at 18:14






      @SebastianPalma it will raise an error about uninitialized constant before method profile will be tried.

      – Зелёный
      Mar 1 at 18:14














      As an aside try and safe navigation &. are not exactly equivalent Spec

      – engineersmnky
      Mar 1 at 20:13






      As an aside try and safe navigation &. are not exactly equivalent Spec

      – engineersmnky
      Mar 1 at 20:13














      ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

      – 3limin4t0r
      Mar 1 at 21:54





      ^ a&.b = a.nil? ? nil : a.b whereas a.try(:b) = a.respond_to?(:b) ? a.b : nil

      – 3limin4t0r
      Mar 1 at 21:54













      3














      If you are using a Ruby version greater than 2.3, you can use the safe operator instead. For example,



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


      Isn't that neat?






      share|improve this answer



























        3














        If you are using a Ruby version greater than 2.3, you can use the safe operator instead. For example,



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


        Isn't that neat?






        share|improve this answer

























          3












          3








          3







          If you are using a Ruby version greater than 2.3, you can use the safe operator instead. For example,



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


          Isn't that neat?






          share|improve this answer













          If you are using a Ruby version greater than 2.3, you can use the safe operator instead. For example,



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


          Isn't that neat?







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 1 at 17:00









          bitsapienbitsapien

          1,075823




          1,075823





















              3














              Just for fun



              Roll your own:



              # concerns/deep_try.rb

              module DeepTry
              def deep_try(*methods)
              methods.reduce(self) receiver.try(method)
              end
              end

              # user.rb (or anywhere else you want it)
              extend DeepTry


              That would let you safely call the following:



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


              You could also use on an instance level:



              @user.extend(DeepTry).deep_try(:profile, :settings, :card, :options)





              share|improve this answer

























              • tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

                – 3limin4t0r
                Mar 1 at 22:13












              • Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

                – SRack
                Mar 7 at 11:45















              3














              Just for fun



              Roll your own:



              # concerns/deep_try.rb

              module DeepTry
              def deep_try(*methods)
              methods.reduce(self) receiver.try(method)
              end
              end

              # user.rb (or anywhere else you want it)
              extend DeepTry


              That would let you safely call the following:



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


              You could also use on an instance level:



              @user.extend(DeepTry).deep_try(:profile, :settings, :card, :options)





              share|improve this answer

























              • tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

                – 3limin4t0r
                Mar 1 at 22:13












              • Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

                – SRack
                Mar 7 at 11:45













              3












              3








              3







              Just for fun



              Roll your own:



              # concerns/deep_try.rb

              module DeepTry
              def deep_try(*methods)
              methods.reduce(self) receiver.try(method)
              end
              end

              # user.rb (or anywhere else you want it)
              extend DeepTry


              That would let you safely call the following:



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


              You could also use on an instance level:



              @user.extend(DeepTry).deep_try(:profile, :settings, :card, :options)





              share|improve this answer















              Just for fun



              Roll your own:



              # concerns/deep_try.rb

              module DeepTry
              def deep_try(*methods)
              methods.reduce(self) receiver.try(method)
              end
              end

              # user.rb (or anywhere else you want it)
              extend DeepTry


              That would let you safely call the following:



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


              You could also use on an instance level:



              @user.extend(DeepTry).deep_try(:profile, :settings, :card, :options)






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 7 at 11:45

























              answered Mar 1 at 17:46









              SRackSRack

              4,50941738




              4,50941738












              • tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

                – 3limin4t0r
                Mar 1 at 22:13












              • Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

                – SRack
                Mar 7 at 11:45

















              • tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

                – 3limin4t0r
                Mar 1 at 22:13












              • Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

                – SRack
                Mar 7 at 11:45
















              tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

              – 3limin4t0r
              Mar 1 at 22:13






              tbh, I'd leave out the extend ActiveSupport::Concern and class_methods do. You can use extend inside a class (instead of include) to do the same thing. This also allow you to apply it over instances, without adding it to the class. eg. User.last.extend(DeepTry).deep_try(:profile, :settings, :card, :options)

              – 3limin4t0r
              Mar 1 at 22:13














              Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

              – SRack
              Mar 7 at 11:45





              Thanks a lot @3limin4t0r - great steer. I've updated the answer to reflect this.

              – SRack
              Mar 7 at 11:45











              0














              I know this is out in left field, but you know, diversity in thinking.



              I have created the (very tiny) insouciant gem that allows code to be executed with worrying about errors. Using this gem the code would look like:



              insouciant(nil) User.profile.settings.card.options 


              with the slight added "benefit" of catching all standard errors, not just nil method errors. The nil value is returned on an error. You can replaced it with some other value if that makes more sense in your application.



              Omitting the parameter entirely will return the error message as a string.






              share|improve this answer



























                0














                I know this is out in left field, but you know, diversity in thinking.



                I have created the (very tiny) insouciant gem that allows code to be executed with worrying about errors. Using this gem the code would look like:



                insouciant(nil) User.profile.settings.card.options 


                with the slight added "benefit" of catching all standard errors, not just nil method errors. The nil value is returned on an error. You can replaced it with some other value if that makes more sense in your application.



                Omitting the parameter entirely will return the error message as a string.






                share|improve this answer

























                  0












                  0








                  0







                  I know this is out in left field, but you know, diversity in thinking.



                  I have created the (very tiny) insouciant gem that allows code to be executed with worrying about errors. Using this gem the code would look like:



                  insouciant(nil) User.profile.settings.card.options 


                  with the slight added "benefit" of catching all standard errors, not just nil method errors. The nil value is returned on an error. You can replaced it with some other value if that makes more sense in your application.



                  Omitting the parameter entirely will return the error message as a string.






                  share|improve this answer













                  I know this is out in left field, but you know, diversity in thinking.



                  I have created the (very tiny) insouciant gem that allows code to be executed with worrying about errors. Using this gem the code would look like:



                  insouciant(nil) User.profile.settings.card.options 


                  with the slight added "benefit" of catching all standard errors, not just nil method errors. The nil value is returned on an error. You can replaced it with some other value if that makes more sense in your application.



                  Omitting the parameter entirely will return the error message as a string.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 1 at 17:51









                  Peter CamilleriPeter Camilleri

                  1,5221217




                  1,5221217



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54949112%2fbetter-alternative-to-try-method%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      1928 у кіно

                      Захаров Федір Захарович

                      Ель Греко