Photo by Zumberto _ from FreeImages
We can't function without operators in any language, and sometimes working with them can be a bit confusing. But, did you know that there are some lesser known operators in Ruby that can make your life easier?
In this post I would like to explore the Safe Navigation Operator a bit further.
Lately I have been going through old projects to refactor, clean up my code, and get things live. I have been noticing many places where this smooth operator would have been useful.
What exactly does it do?
The Safe Navigation Operator returns nil if a method is called on a nil object.
Why should we care?
Well, it is best to avoid throwing errors at your users. It's not very nice!
Let's take a look at a quick example:
patch '/pizzas/:id' do
@pizza = Pizza.find_by(id: params[:id])
if @pizza && @pizza.user == current_user
if @pizza.update(params[:pizza])
redirect to "/pizzas/#{@pizza.id}"
else
erb :'/pizzas/edit'
end
else
redirect to "/pizzas"
end
end
In the snippet above, I am checking to see if there is indeed an instance of the Pizza class found by id, and if there is, does that instance's user match the current user?
if @pizza && @pizza.user == current_user
This works just fine, but it would be cleaner to write:
if @pizza&.user == current_user
Why not use .try? Well because that is provided by ActiveSupport as part of Ruby on Rails, which is awesome! However if you wish to remove this dependency, just use the Safe Navigation Operator instead of .try.
Top comments (0)