Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie rails question: elegant way to deal with nil values in .each loops?

Just meddling with Rails at the moment, and struggling to figure out how to escape "you have a nil object when you didn't expect it" errors . At the moment I'm escaping each of them with an "unless object.nil?" message, but it's getting pretty ugly. Case in point:

unless params[:professiontypeinfo].nil?
  unless params[:professiontypeinfo][professiontypeid].nil?
    unless params[:professiontypeinfo][professiontypeid]["industrybodies"].nil?
        @professional.professional_specialties.find_by_profession_type_id(professiontypeid).industry_bodies = IndustryBody.find_all_by_id(params[:professiontypeinfo][professiontypeid]["industrybodies"])
    end
  end
end

Soo...what's the correct/graceful way of escaping these things?

like image 465
PlankTon Avatar asked Dec 05 '25 07:12

PlankTon


2 Answers

Hash[] returns false when the requested key is missing, so

if params[key]

will return false if params does not have key

And-ed conditions short-circuit (ie stop evaluating when the first condition is false), so the following will work even when key is missing:

if params[key] && params[key][sub_key]
like image 170
zetetic Avatar answered Dec 07 '25 22:12

zetetic


The below method will evaluate each condition in order and exit if a condition fails without moving onto the next

unless params[:professiontypeinfo] && params[:professiontypeinfo][professiontypeid] && params[:professiontypeinfo][professiontypeid]["industrybodies"]

Update: based on Jimmy's comments =]

like image 33
Coderama Avatar answered Dec 07 '25 21:12

Coderama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!