Sha256: d17e622135af71f404a930578a2ebbc046ff6c960b13cedc67508691c72f2aff

Contents?: true

Size: 1.19 KB

Versions: 9

Compression:

Stored size: 1.19 KB

Contents

require 'rest-core/middleware'

class RestCore::FollowRedirect
  def self.members; [:max_redirects]; end
  include RestCore::Middleware

  def call env, &k
    e = env.merge('follow_redirect.max_redirects' =>
                    env['follow_redirect.max_redirects'] ||
                    max_redirects(env))

    if e[DRY]
      app.call(e, &k)
    else
      app.call(e){ |res| process(res, k) }
    end
  end

  def process res, k
    return k.call(res) if res['follow_redirect.max_redirects'] <= 0
    return k.call(res) if ![301,302,303,307].include?(res[RESPONSE_STATUS])
    return k.call(res) if  [301,302    ,307].include?(res[RESPONSE_STATUS]) &&
                          ![:get, :head    ].include?(res[REQUEST_METHOD])

    location = [res[RESPONSE_HEADERS]['LOCATION']].flatten.first
    meth     = if res[RESPONSE_STATUS] == 303
                 :get
               else
                 res[REQUEST_METHOD]
               end

    call(res.merge(REQUEST_PATH    => location,
                   REQUEST_METHOD  => meth    ,
                   REQUEST_PAYLOAD => {}      ,
                   'follow_redirect.max_redirects' =>
                     res['follow_redirect.max_redirects'] - 1), &k)
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rest-core-3.0.0 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.1.2 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.1.1 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.1.0 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.0.4 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.0.3 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.0.2 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.0.1 lib/rest-core/middleware/follow_redirect.rb
rest-core-2.0.0 lib/rest-core/middleware/follow_redirect.rb