try() lets you call methods on an object without having to worry about the possibility of that object being
nil and thus raising an exception. I know I sometimes forget about it, and I’ve looked at enough code from other developers to know that I’m not the only one. So today I’d like to give you a brief introduction to the method (and hopefully ingrain it a little deeper into my own brain). Let’s look at some very simple code from a Rails view.
Here’s a simple example of code you might replace with
try(). Say you’ve got a (rather contrived)
Product model in your project. A
Product may or may not have a known manufacturer, and some links you only want to display if a user is logged in and has administrator rights:
Like I said, it’s contrived, but it should give you the idea.
try() can help us in a couple of places here:
You can pass arguments and blocks to
You can chain multiple
try() methods together. In another contrived example, say you’ve got a method in your
Manufacturer model that sends the manufacturer a message whenever called.
You can start with the Rails docs on try(). Rails’ inclusion of
try() was inspired by Chris Wanstrath’s post about adding try() to Ruby. Raymond Law at Intridea has a clever way to chain multiple calls to try(). And Scott Harvey has shared a more practical example of try().
I stand with the Black community against systemic racism, police violence and brutality, intolerance, and hate in the United States and worldwide. We must all demand better from our leaders, and ourselves. Stop tolerating intolerance.
While you're here, please consider making a donation to Black Girls CODE, who do great, important work to provide opportunity to underprivileged girls interested in tech, or any organization working toward equity and safety for all, not just the privileged. Thank you.
If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.
Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.