.try in Ruby on Rails

Throughout the course of module 2 at Flatiron School (Ruby on Rails), I kept seeing the .try method being used in examples (particularly for password authentication) and wasn’t really sure what the method was doing. It just seemed like some Rails magic, as everything else does, and I wasn’t sure how to use it correctly — so I did some research, and it’s actually a really useful method.

Example code where .try would be helpful in cleaning up code

One place where .try is really useful and often used is in a log in method//sessions controller. Here, on line 18, the code is a little more complex than necessary. First, I find the user by the email they put into the login form. Then, to authenticate the user’s password, I first have to say if there is a user (if @ user), AND if that user’s password is correct, then log that user in. It’s a little repetitive, and a place where .try comes in handy.

Slightly cleaner code using .try

What the .try method does (according to the documentation) is it invokes the method called as the first argument on .try, and calls that on the receiver, just like any other method. Where it’s useful is that if the receiver (here, @ user) doesn’t respond to the method, instead of breaking and raising an error, it just returns nil. So! In a login method, you can see where this would be useful. If the user puts in the wrong email or doesn’t have an account, they won’t exist in the database and won’t be found by the User.find_by method. But then the next line won’t break because of that, and there isn’t an extra if and statement in the code.

Another example use of the .try method

This can be used in a number of places to clean up the code and prevent errors if a user doesn’t exist, or if, in the case above, a user has been deleted or the activity itself has been deleted and therefore no longer has an owner. This code (using the public activity gem to display a timeline of user activity) was breaking when a user deleted their comment, until I went back into the code and added the .try method.

It’s pretty straightforward to use, although it doesn’t seem easy at first glance! I will definitely continue using .try in my Rails code to clean things up a bit and prevent errors, and hopefully this blog helped clear it up for you, too.