From a5ac2a1b77c760b2849c2aa09cc53808a6c0d7a2 Mon Sep 17 00:00:00 2001 From: Russell Garner Date: Thu, 11 Apr 2024 18:10:52 +0100 Subject: [PATCH] Fix NoMethodError when cookies == :none When tracking with no visit, ``` Ahoy.cookies = :none Ahoy::Tracker.new.track_event(:would_fail) ``` would raise NoMethodError: undefined method `remote_ip' for nil. Since we explicitly don't have a request, allow visitor_token_helper to fall back on generate_id by not calling visitor_anonymity_set when there is no request. --- lib/ahoy/tracker.rb | 2 +- test/tracker_test.rb | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/ahoy/tracker.rb b/lib/ahoy/tracker.rb index 3fedfaec..180ce1c9 100644 --- a/lib/ahoy/tracker.rb +++ b/lib/ahoy/tracker.rb @@ -216,7 +216,7 @@ def visit_token_helper def visitor_token_helper @visitor_token_helper ||= begin token = existing_visitor_token - token ||= visitor_anonymity_set unless Ahoy.cookies? + token ||= visitor_anonymity_set unless Ahoy.cookies? || request.nil? token ||= generate_id unless Ahoy.api_only token end diff --git a/test/tracker_test.rb b/test/tracker_test.rb index 9e7b8947..25c1166f 100644 --- a/test/tracker_test.rb +++ b/test/tracker_test.rb @@ -11,6 +11,21 @@ def test_no_request assert_nil event.user_id end + def test_no_request_with_cookies_none + old_cookies = Ahoy.cookies + Ahoy.cookies = :none + + ahoy = Ahoy::Tracker.new + ahoy.track("Some event", some_prop: true) + + event = Ahoy::Event.last + assert_equal "Some event", event.name + assert_equal({"some_prop" => true}, event.properties) + assert_nil event.user_id + ensure + Ahoy.cookies = old_cookies + end + def test_no_cookies request = ActionDispatch::TestRequest.create