Skip to content

Commit

Permalink
Fix net-http deprecation warning for Ruby 3.4
Browse files Browse the repository at this point in the history
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!'
```
  • Loading branch information
Earlopain committed Nov 19, 2024
1 parent 9ff63ac commit 67c0695
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions lib/webmock/http_lib_adapters/net_http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 67c0695

Please sign in to comment.