diff --git a/lib/faraday/deprecated_constant.rb b/lib/faraday/deprecated_constant.rb new file mode 100644 index 000000000..609842949 --- /dev/null +++ b/lib/faraday/deprecated_constant.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +module Faraday + # Allows for the deprecation of constants between versions of Faraday + # + # rubocop:disable Style/MethodMissingSuper, Style/MissingRespondToMissing + class DeprecatedConstant < Module + def self.new(*args, &block) + object = args.first + return object unless object + + super + end + + def initialize(old_const, new_const) + @old_const = old_const + @new_const = new_const + end + + # TODO: use match? once Faraday drops Ruby 2.3 support + instance_methods.each do |method_name| + undef_method method_name if /^__|^object_id$/.match(method_name).nil? + end + + def inspect + @new_const.inspect + end + + def class + @new_const.class + end + + private + + def const_missing(name) + warn + @new_const.const_get(name) + end + + def method_missing(method_name, *args, &block) + warn + @new_const.__send__(method_name, *args, &block) + end + + def warn + puts( + "DEPRECATION WARNING: #{@old_const} is deprecated! " \ + "Use #{@new_const} instead." + ) + end + end + # rubocop:enable Style/MethodMissingSuper, Style/MissingRespondToMissing +end diff --git a/lib/faraday/error.rb b/lib/faraday/error.rb index fd58354db..75c913be5 100644 --- a/lib/faraday/error.rb +++ b/lib/faraday/error.rb @@ -1,5 +1,8 @@ # frozen_string_literal: true +require 'faraday/deprecated_constant' + +# Faraday namespace. module Faraday # Faraday error base class. class Error < StandardError @@ -97,4 +100,15 @@ class ParsingError < Error # @see Faraday::Request::Retry class RetriableResponse < Error end + + %i[ClientError ConnectionFailed ResourceNotFound + ParsingError TimeoutError SSLError RetriableResponse].each do |const| + Error.const_set( + const, + Faraday::DeprecatedConstant.new( + "Faraday::Error::#{const}", + Faraday.const_get(const) + ) + ) + end end diff --git a/spec/faraday/error_spec.rb b/spec/faraday/error_spec.rb index 98a31b84e..45ed04e11 100644 --- a/spec/faraday/error_spec.rb +++ b/spec/faraday/error_spec.rb @@ -41,5 +41,26 @@ it { expect(subject.message).to eq('["error1", "error2"]') } it { expect(subject.inspect).to eq('#>') } end + + context 'maintains backward-compatibility until 1.0' do + it 'does not raise an error for nested error classes but prints an error message' do + error_message, error = with_warn_squelching { Faraday::Error::ClientError.new('foo') } + + expect(error).to be_a Faraday::ClientError + expect(error_message).to eq( + "DEPRECATION WARNING: Faraday::Error::ClientError is deprecated! Use Faraday::ClientError instead.\n" + ) + end + end + + def with_warn_squelching + stdout_catcher = StringIO.new + original_stdout = $stdout + $stdout = stdout_catcher + result = yield if block_given? + [stdout_catcher.tap(&:rewind).string, result] + ensure + $stdout = original_stdout + end end end