From 67c0695c922b46aa2230cf7ac6d72e4e69cafad7 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Tue, 19 Nov 2024 12:46:49 +0100 Subject: [PATCH] Fix `net-http` deprecation warning for Ruby 3.4 This old constant was deprecated in 2001 and will now be removed in Ruby 3.5 On Ruby 3.4, removing a deprecated constant will warn: > /home/user/code/webmock/lib/webmock/http_lib_adapters/net_http.rb:55: warning: constant Net::HTTPSession is deprecated It fixes this error on Ruby 3.5: ``` /usr/local/bundle/bundler/gems/webmock-9ff63ac7c845/lib/webmock/http_lib_adapters/net_http.rb:25:in 'Module#remove_const': constant Net::HTTPSession not defined (NameError) Net.send(:remove_const, :HTTPSession) ^^^^^ from /usr/local/bundle/bundler/gems/webmock-9ff63ac7c845/lib/webmock/http_lib_adapters/net_http.rb:25:in 'WebMock::HttpLibAdapters::NetHttpAdapter.disable!' ``` --- lib/webmock/http_lib_adapters/net_http.rb | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/webmock/http_lib_adapters/net_http.rb b/lib/webmock/http_lib_adapters/net_http.rb index fd2a4a6f..eaff3617 100644 --- a/lib/webmock/http_lib_adapters/net_http.rb +++ b/lib/webmock/http_lib_adapters/net_http.rb @@ -12,19 +12,25 @@ class NetHttpAdapter < HttpLibAdapter adapter_for :net_http OriginalNetHTTP = Net::HTTP unless const_defined?(:OriginalNetHTTP) + # This will be removed in Ruby 3.5. In Ruby 3.4, const_remove will warn. + HAS_LEGACY_CONSTANT = Net.const_defined?(:HTTPSession) def self.enable! Net.send(:remove_const, :HTTP) - Net.send(:remove_const, :HTTPSession) Net.send(:const_set, :HTTP, @webMockNetHTTP) - Net.send(:const_set, :HTTPSession, @webMockNetHTTP) + if HAS_LEGACY_CONSTANT + remove_silently(Net, :HTTPSession) + Net.send(:const_set, :HTTPSession, @webMockNetHTTP) + end end def self.disable! Net.send(:remove_const, :HTTP) - Net.send(:remove_const, :HTTPSession) Net.send(:const_set, :HTTP, OriginalNetHTTP) - Net.send(:const_set, :HTTPSession, OriginalNetHTTP) + if HAS_LEGACY_CONSTANT + remove_silently(Net, :HTTPSession) + Net.send(:const_set, :HTTPSession, OriginalNetHTTP) + end #copy all constants from @webMockNetHTTP to original Net::HTTP #in case any constants were added to @webMockNetHTTP instead of Net::HTTP @@ -37,6 +43,14 @@ def self.disable! end end + def self.remove_silently(mod, const) #:nodoc: + # Don't warn on removing the deprecated constant + verbose, $VERBOSE = $VERBOSE, nil + mod.send(:remove_const, const) + ensure + $VERBOSE = verbose + end + @webMockNetHTTP = Class.new(Net::HTTP) do class << self def socket_type