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

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.

The original open_uri takes *args but then doesn’t do anything with them. Assume we can only handle a hash.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/open-uri/redirections_patch.rb', line 32

def self.open_uri(name, *rest, &block)
  mode, _, rest = OpenURI.scan_open_optional_arguments(*rest)
  options = rest.first if !rest.empty? && Hash === rest.first

  allow_redirections = options.delete :allow_redirections if options
  case allow_redirections
  when :safe
    class << self
      remove_method :redirectable?
      alias_method  :redirectable?, :redirectable_safe?
    end
  when :all
    class << self
      remove_method :redirectable?
      alias_method  :redirectable?, :redirectable_all?
    end
  else
    class << self
      remove_method :redirectable?
      alias_method  :redirectable?, :redirectable_cautious?
    end
  end

  self.open_uri_original name, *rest, &block
end

.open_uri_originalObject



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

alias_method :open_uri_original, :open_uri

.redirectable_all?(uri1, uri2) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/open-uri/redirections_patch.rb', line 20

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

.redirectable_safe?(uri1, uri2) ⇒ Boolean

Returns:

  • (Boolean)


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

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