Question

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?

Was it helpful?

Solution

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

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

Check here for more info.

OTHER TIPS

Check it for nil or rescue the exception yourself.

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top