views:

233

answers:

3

I've got this line of code:

if request.user_agent.include?("iPhone") then

But I'm occasionally getting this error:

"undefined method `include?' for nil:NilClass"

When checking logs on the error, there isn't a "HTTP_USER_AGENT" for the user that is getting the error.

So how can I fix that line so it doesn't throw an error if there isn't an HTTP_USER_AGENT?

A: 

Check it for nil or rescue the exception yourself.

Azeem.Butt
+1  A: 

For Rails 2.3.xx you can also use Object#try

request.user_agent.try(:include?, 'iphone')

Check here for more info.

pantulis
A: 

NSD is right.

You could also use try as a short cut:

request.user_agent.try(:include?, "iPhone")

try will not error when its receiver is nil, so you can chain them together, like this:

foo.try(:bar).try(:baz)
Luke Francl