Try the "try" method and get rescued
Have you ever used
Here we are finding the first admin. Then accessing his/her address and then try to reset it. But what if that admin doesnt really have any address. I mean
Actually
So lets start using try for the cases where we are not sure about the presence of any object.
'try'
method in Ruby on Rails ( yes it is provided by rails not ruby ). I started loving this method so much. As the method name implies you will try to do something. If anyhow it fails it doesnt get fired on you by throwing any ugly exceptions. Look at the documentation. You may have already guessed the idea. But still lets work with a simple example.User.admins.first.try(:address).try(:reset)instead of
User.admins.first.address.reset
Here we are finding the first admin. Then accessing his/her address and then try to reset it. But what if that admin doesnt really have any address. I mean
User.admins.first.address.first.address
is nil. Then a NoMethodError
for nil
class would be waiting for you. But with the try
you are safe. WHY?Actually
try
does nothing but invoking the Object#send
method with the function name and the passed parameters. You can even pass a block through try. And apart from this Object#try
method, you will have a Nil#try
method also. So if by any chance your calling object is nil
, then the result is also nil
. In this way either the above line will try to reset the address of the first admin, or just will remain silent if no addresses found.So lets start using try for the cases where we are not sure about the presence of any object.
Comments
Post a Comment