Skip to content

Commit 1ae43da

Browse files
committed
feat: only print metrics warning once per thread
1 parent e139999 commit 1ae43da

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

lib/pact/support/metrics.rb

+21-7
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,21 @@ module Support
99
class Metrics
1010

1111
def self.report_metric(event, category, action, value = 1)
12+
do_once_per_thread(:pact_metrics_message_shown) do
13+
if track_events?
14+
Pact.configuration.output_stream.puts "mock WARN: Please note: we are tracking events anonymously to gather important usage statistics like Pact-Ruby version and operating system. To disable tracking, set the 'PACT_DO_NOT_TRACK' environment variable to 'true'."
15+
end
16+
end
17+
1218
in_thread do
1319
begin
1420
if track_events?
15-
Pact.configuration.output_stream.puts "WARN: Please note: we are tracking events anonymously to gather important usage statistics like Pact-Ruby version and operating system. To disable tracking, set the 'PACT_DO_NOT_TRACK' environment variable to 'true'."
16-
17-
uri = URI('https://www.google-analytics.com/collect')
18-
req = Net::HTTP::Post.new(uri)
19-
req.set_form_data(create_tracking_event(event, category, action, value))
21+
uri = URI('https://www.google-analytics.com/collect')
22+
req = Net::HTTP::Post.new(uri)
23+
req.set_form_data(create_tracking_event(event, category, action, value))
2024

21-
Net::HTTP.start(uri.hostname, uri.port, read_timeout:2, open_timeout:2, :use_ssl => true ) do |http|
22-
http.request(req)
25+
Net::HTTP.start(uri.hostname, uri.port, read_timeout:2, open_timeout:2, :use_ssl => true ) do |http|
26+
http.request(req)
2327
end
2428
end
2529
rescue StandardError => e
@@ -42,6 +46,16 @@ def self.in_thread
4246
end
4347
end
4448

49+
# Not super safe to use the thread, but it's good enough for this usecase
50+
def self.do_once_per_thread(key)
51+
result = nil
52+
if !Thread.current[key]
53+
result = yield
54+
end
55+
Thread.current[key] = true
56+
result
57+
end
58+
4559
def self.create_tracking_event(event, category, action, value)
4660
{
4761
"v" => 1,

0 commit comments

Comments
 (0)