This question already has an answer here:
I have the following very ugly ruby code in a rails app I'm working on:
if params.present?
if params[:search].present?
if params[:search][:tags_name_in].present?
...
end
end
end
All I'm trying to ask is whether params[:search][:tags_name_in] has been defined, but because params, and params[:search], and params[:search][:tags_name_in] might all be nil, if I use...
if params[:search][:tags_name_in].present?
... I get an error if there are no params or no search params.
Surely there must be a better way to do this... suggestions??
I usually end up doing something like this:
Although if you don't mind testing against nils in your if statement you could also do this:
This will not throw an error because ruby short-circuits the && operator.
Haha, if you want to be terrible and monkeypatch nil:
I would recommend a short-circuited if like the other answers suggest, though.
You have many choices that will return the value of
params[:search][:tags_name_in]
ornil
ifparams[:search]
isnil
.Clear but lengthy:
Using
try
(fromactive_support
):Using rescue:
Using
fetch
:Note that
fetch
can sometime be used to avoid theif
altogether, in particular if there is nothing to do when the param is not specified:Params will always be defined, so you can remove that.
To reduce the amount of code you can do
If
params[:search]
is not defined, the condition will short circuit and returnnil
.if you are just trying to see if its defined why not keep it simple and use the defined? function?
You can use andand for this. It handles this exact situation:
if params[:search].andand[:tags_name_in].andand.present?