nitinsavant nitinsavant - 9 months ago 36
Ruby Question

Checking if Nokogiri object is nil before accessing text method

I'm using Nokogiri to search through XML that I received from an API.

fiber = doc.xpath("/*[name()='food']/*[name()='servings']/*

Sometimes though, the child element (e.g. fiber) is missing from the response. In this case, Nokogiri returns a nil object and my code throws the appropriate exception (undefined method `text' for nil:NilClass) because I'm trying to access the 'text' method of a nil object.

What's a clean and fast way to check if the child element (e.g. fiber) exists before actually trying to call the 'text' method on it? If it doesn't exist, I'd like to set the value to 0. I'm also doing this for several other child elements (e.g. calories, carbohydrates, etc.)


You can use "try" for those cases

fiber = doc.xpath("/*[name()='food']/*[name()='servings']/*

It returns nil if first is nil, and it calles text if it's not nil

If you need a default value in case it's nil you can do

fiber = doc.xpath("/*[name()='food']/*[name()='servings']/*
     [name()='serving']/*[name()='fiber']").first.try(:text) or 'default'