I'm interested in getting the nested 'name' parameter of a params hash. Calling something like
params[:subject][:name]
throws an error when params[:subject] is empty. To avoid this error I usually write something like this:
if params[:subject] && params[:subject][:name]
Is there a cleaner way to implement this?
Not really. You can try
fetch
ortry
(from ActiveSupport) but it's not much cleaner than what you already have.More info here:
UPDATE: Forgot about
andand
:andand
lets you do:Similarly, you can use
maybe
from the Ick library per the answer above.When I have same problem in coding, I sometimes use `rescue'.
This is not good manners, but I think it is simple way.
EDIT: I don't use this way often anymore. I recommend
try
orfetch
.I wrote Dottie for just this use case — reaching deep into a hash without first knowing whether the entire expected tree exists. The syntax is more succinct than using
try
(Rails) ormaybe
(Ick). For example:Check out the docs if you want to see more: https://github.com/nickpearson/dottie
Check Ick's maybe. You don't need to significantly refactor your code, just intersperse maybe proxies when necessary:
The same author (raganwald) also wrote andand, with the same idea.
You can avoid the double hash access with an inline assignment:
I cross posted this from my answer over here:
How to check if params[:some][:field] is nil?
I have been looking for a better solution too.
So I figured let's use
try
a different way to test for a nested key being set:It's not bad. You get
nil
vs.false
if it's not set. You also gettrue
if the param is set tonil
.