Sha256: 177e2f2a4bb5703f2f5dd1de5e2fffedf00de8e7e739dd1117ca57437454b918

Contents?: true

Size: 1.13 KB

Versions: 9

Compression:

Stored size: 1.13 KB

Contents

module Credly
  module Response
    class RedirectLimitReached < Faraday::Error::ClientError
      attr_reader :response

      def initialize(response)
        super "too many redirects; last one to: #{response['location']}"
        @response = response
      end
    end

    class FollowRedirects < Faraday::Middleware
      REDIRECTS = [301, 302, 303, 307]
      # default value for max redirects followed
      FOLLOW_LIMIT = 3

      def initialize(app, options = {})
        super(app)
        @options = options
        @follow_limit = options[:limit] || FOLLOW_LIMIT
      end

      def call(env)
        process_response(@app.call(env), @follow_limit)
      end

      def process_response(response, follows)
        response.on_complete do |env|
          if redirect? response
            raise RedirectLimitReached, response if follows.zero?
            env[:url] += response['location']
            env[:method] = :get
            response = process_response(@app.call(env), follows - 1)
          end
        end
        response
      end

      def redirect?(response)
        REDIRECTS.include? response.status
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
credly-0.0.9 lib/credly/response/follow_redirects.rb
credly-0.0.8 lib/credly/response/follow_redirects.rb
credly-0.0.7 lib/credly/response/follow_redirects.rb
credly-0.0.6 lib/credly/response/follow_redirects.rb
credly-0.0.5 lib/credly/response/follow_redirects.rb
credly-0.0.4 lib/credly/response/follow_redirects.rb
credly-0.0.3 lib/credly/response/follow_redirects.rb
credly-0.0.2 lib/credly/response/follow_redirects.rb
credly-0.0.1 lib/credly/response/follow_redirects.rb