views:

69

answers:

3

"output" is a serialized OpenStruct.

def title
  try(:output).try(:data).try(:title)
end

What would be better? :)

+1  A: 
def try_chain
  yield
rescue NoMethodError
  nil
end

def title
  try_chain { output.data.title }
end
hgimenez
Great answer, thanks!
Jay
A: 

Thoughtbot just talked about this on their blog, using what they call it's a Shallow Nil:

def swallow_nil
  yield
rescue NoMethodError
  nil
end

So, in their example, they could do something like:

campaign = swallow_nil { supporter.politician.campaign }

Or, in your case,

def title
  swallow_nil { output.data.title }
end

However, be aware that any of your bugs will also be swallowed and would be hard to find, specially since it traps every NoMethodErrors, which would be caused from other parts of your code (although if you use testing, this helps a lot).

Another approach would be to use andand, where your code would be then

def title
  output.andand.data.andand.title
end

Not as clean as the swallow_nil one, but probably best to not just ignore everything.

Yaraher
Great answer, thanks!
Jay
A: 

Or simply this:

def title
  output.data.title rescue nil
end
Benjamin Curtis
Very succinct, thanks!
Jay
The problem with this approach is that, if there is something wrong on that chain, you won't notice it after it's too late =P
Yaraher