Module: OpenURI

Defined in:
lib/open-uri/redirections_patch.rb

Overview

Patch to allow open-uri to follow safe (http to https) and unsafe redirections (https to http). Original gist URL: gist.github.com/1271420

Relevant issue: redmine.ruby-lang.org/issues/3719

Source here: github.com/ruby/ruby/blob/trunk/lib/open-uri.rb

Thread-safe implementation adapted from: github.com/obfusk/open_uri_w_redirect_to_https

Class Method Summary collapse

Class Method Details

.open_uri(name, *rest, &block) ⇒ Object

Patches the original open_uri method to accept the :allow_redirections option

:allow_redirections => :safe will allow HTTP => HTTPS redirections. :allow_redirections => :all will allow HTTP => HTTPS and HTTPS => HTTP redirections.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/open-uri/redirections_patch.rb', line 44

def self.open_uri(name, *rest, &block)
  options = self.first_hash_argument(rest)
  allow_redirections = options.delete :allow_redirections if options
  Thread.current[:__open_uri_redirections__] = allow_redirections

  block2 = lambda { |io|
    Thread.current[:__open_uri_redirections__] = nil
    block[io]
  }

  begin
    self.open_uri_original name, *rest, &(block ? block2 : nil)
  ensure
    Thread.current[:__open_uri_redirections__] = nil
  end
end

.open_uri_originalObject



16
# File 'lib/open-uri/redirections_patch.rb', line 16

alias_method :open_uri_original, :open_uri

.redirectable?(uri1, uri2) ⇒ Boolean



19
20
21
22
23
24
25
26
27
28
# File 'lib/open-uri/redirections_patch.rb', line 19

def redirectable?(uri1, uri2)
  case Thread.current[:__open_uri_redirections__]
  when :safe
    redirectable_safe? uri1, uri2
  when :all
    redirectable_all? uri1, uri2
  else
    redirectable_cautious? uri1, uri2
  end
end

.redirectable_all?(uri1, uri2) ⇒ Boolean



34
35
36
# File 'lib/open-uri/redirections_patch.rb', line 34

def redirectable_all?(uri1, uri2)
  redirectable_safe?(uri1, uri2) || (uri1.scheme.downcase == "https" && uri2.scheme.downcase == "http")
end

.redirectable_cautious?Object



17
# File 'lib/open-uri/redirections_patch.rb', line 17

alias_method :redirectable_cautious?, :redirectable?

.redirectable_safe?(uri1, uri2) ⇒ Boolean



30
31
32
# File 'lib/open-uri/redirections_patch.rb', line 30

def redirectable_safe?(uri1, uri2)
  redirectable_cautious?(uri1, uri2) || (uri1.scheme.downcase == "http" && uri2.scheme.downcase == "https")
end