Ahoy Gem 'request' is often nil

127 views Asked by At

I am trying to exclude a range of ip addresses from being tracked with the Ahoy gem. The docs give this example:

Ahoy.exclude_method = lambda do |controller, request|
  request.ip == "192.168.1.1"
end

In the ahoy.rb initializer file I have:

 Ahoy.exclude_method = lambda do |controller, request|
    range = IPAddr.new("66.249.66.0/24")
    range.include?(request.ip) || request.url.split("/").include?("serviceworker.js")
  end

Rollbar is reporting constant errors from the ahoy.rb file:

NoMethodError: [safely] undefined method `ip' for nil:NilClass

Perhaps I don't understand what is a request, but if someone is on my site, I'm presuming there should be a valid non-nil request. Is that right?

Apparently the answer is no, that is not right since obviously a request is often nil, and I'm thinking the next step is to exclude this error from rollbar reporting and move on since the error does not impact user experience on the site. Am I thinking straight on this?

1

There are 1 answers

0
Engineer Waqas On
Ahoy.exclude_method = lambda do |controller, request|
  if request.present? && request&.ip.present?
    range = IPAddr.new("66.249.66.0/24")
    range.include?(IPAddr.new(request.ip)) || request.url.split("/").include?("serviceworker.js")
  else
    false
  end
end

Check the request object and the request IP address is present before accessing it. Also, convert the request IP address to the IPAddr instance before checking if the range includes it.