AppEngine::URLFetch.fetchのfollow_redirectsオプションが効かない

 こんにちは。那由多屋の加藤です。

 GAE/JRubyと戯れる日々ですが、今度はAppEngine::URLFetch.fetchのfollow_redirectsオプションが効かないという現象に遭遇。

 これまでと同じように、appengine-apis-0.0.12のソースコードを眺めてみたら・・・バグってました。念のために本家のリポジトリも確認したところ、既に修正されていました。

 というわけで、appengine-apis-0.0.12の次のバージョンがリリースされるまでのモンキーパッチ。

# 「follow_redirectsオプションを無効にできない不具合」を修正するモンキーパッチ
# リポジトリの最新版では修正済み
# 対象はappengine-apis-0.0.12

module AppEngine
  module URLFetch
    module_function
    def build_urlfetch_request(url, options)  # :nodoc:
      method = options.delete(:method) || 'GET'
      payload = options.delete(:payload)
      headers = options.delete(:headers) || {}
      truncate = options.delete(:allow_truncated)
      follow_redirects = options.delete(:follow_redirects)
      deadline = options.delete(:deadline)
      
      follow_redirects = true if follow_redirects.nil?
      
      unless options.empty?
        raise ArgumentError, "Unsupported options #{options.inspect}."
      end
      
      begin
        method = HTTPMethod.value_of(method.to_s.upcase)
      rescue java.lang.IllegalArgumentException
        raise ArgumentError, "Invalid method #{method.inspect}."
      end
      
      if truncate
        options = FetchOptions::Builder.allow_truncate
      else
        options = FetchOptions::Builder.disallow_truncate
      end
      if follow_redirects
        options.follow_redirects
      else
        options.do_not_follow_redirects
      end
      
      options.set_deadline(deadline) if deadline
      
      url = java.net.URL.new(url) unless url.java_kind_of? java.net.URL
      request = HTTPRequest.new(url, method, options)
      
      iterator = if headers.respond_to?(:canonical_each)
        :canonical_each
      else
        :each
      end
      
      headers.send(iterator) do |name, value|
        request.set_header(HTTPHeader.new(name, value))
      end
      
      if payload
        request.set_payload(payload.to_java_bytes)
      end
      
      return request
    end
  end
end