Skip to content

Commit

Permalink
Merge pull request #1081 from Earlopain/net-http-adapter-ruby-3.4
Browse files Browse the repository at this point in the history
Resolve `net-http` adapter deprecation Ruby 3.4
  • Loading branch information
koic authored Feb 6, 2025
2 parents 9ff63ac + 67c0695 commit 2b963cb
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 2b963cb

Please sign in to comment.