Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Nils in an IF statement [duplicate]

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??

like image 564
Andrew Avatar asked Mar 22 '11 15:03

Andrew


4 Answers

if you are just trying to see if its defined why not keep it simple and use the defined? function?

if defined?(params[:search][:tags_name_in])
like image 117
Will Ayd Avatar answered Nov 06 '22 14:11

Will Ayd


Params will always be defined, so you can remove that.

To reduce the amount of code you can do

if params[:search] && params[:search][:tags_name_in]
  #code
end

If params[:search] is not defined, the condition will short circuit and return nil.

like image 21
Mike Lewis Avatar answered Nov 06 '22 15:11

Mike Lewis


You can use andand for this. It handles this exact situation:

if params[:search].andand[:tags_name_in].andand.present?

like image 4
ryeguy Avatar answered Nov 06 '22 14:11

ryeguy


You have many choices that will return the value of params[:search][:tags_name_in] or nil if params[:search] is nil.

Clear but lengthy:

params[:search] && params[:search][:tags_name_in]

Using try (from active_support):

params[:search].try(:[], :tags_name_in)

Using rescue:

params[:search][:tags_name_in] rescue nil

Using fetch:

params.fetch(:search, {})[:tags_name_in]

Note that fetch can sometime be used to avoid the if altogether, in particular if there is nothing to do when the param is not specified:

def deal_with_tags
  MyModel.where :tags => params.fetch(:search){ return }[:tags_name_in]
end
like image 4
Marc-André Lafortune Avatar answered Nov 06 '22 14:11

Marc-André Lafortune