Namespace
Methods
D
H
M
U
Constants
Gems = RubyGems
 
Class Public methods
download(url, name, dir = nil, ims = true, options = {})

::download(url, name, [dir, [ims]])

Update a file from url if newer version is available. Creates the file if the file doesn't yet exist; however, the directory where the file is being created has to exist already. If ims is false, always download url regardless of its last modified time.

Example usage:

download 'http://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt',
         'UnicodeData.txt', 'enc/unicode/data'
# File tool/downloader.rb, line 118
def self.download(url, name, dir = nil, ims = true, options = {})
  file = under(dir, name)
  if ims.nil? and File.exist?(file)
    if $VERBOSE
      $stdout.puts "#{name} already exists"
      $stdout.flush
    end
    return true
  end
  url = URI(url)
  if $VERBOSE
    $stdout.print "downloading #{name} ... "
    $stdout.flush
  end
  begin
    data = url.read(options.merge(http_options(file, ims.nil? ? true : ims)))
  rescue OpenURI::HTTPError => http_error
    if http_error.message =~ /^304 / # 304 Not Modified
      if $VERBOSE
        $stdout.puts "not modified"
        $stdout.flush
      end
      return true
    end
    raise
  rescue Timeout::Error
    if ims.nil? and File.exist?(file)
      puts "Request for #{url} timed out, using old version."
      return true
    end
    raise
  rescue SocketError
    if ims.nil? and File.exist?(file)
      puts "No network connection, unable to download #{url}, using old version."
      return true
    end
    raise
  end
  mtime = nil
  open(file, "wb", 0600) do |f|
    f.write(data)
    f.chmod(mode_for(data))
    mtime = data.meta["last-modified"]
  end
  if mtime
    mtime = Time.httpdate(mtime)
    File.utime(mtime, mtime, file)
  end
  if $VERBOSE
    $stdout.puts "done"
    $stdout.flush
  end
  true
rescue => e
  raise "failed to download #{name}\n#{e.message}: #{url}"
end
http_options(file, since)
# File tool/downloader.rb, line 90
def self.http_options(file, since)
  options = {}
  if since
    case since
    when true
      since = (File.mtime(file).httpdate rescue nil)
    when Time
      since = since.httpdate
    end
    if since
      options['If-Modified-Since'] = since
    end
  end
  options['Accept-Encoding'] = '*' # to disable Net::HTTP::GenericRequest#decode_content
  options
end
https()
# File tool/downloader.rb, line 34
def self.https
  if @@https != 'https'
    warn "*** using http instead of https ***"
  end
  @@https
end
mode_for(data)
# File tool/downloader.rb, line 86
def self.mode_for(data)
  /\A#!/ =~ data ? 0755 : 0644
end
under(dir, name)
# File tool/downloader.rb, line 175
def self.under(dir, name)
  dir ? File.join(dir, File.basename(name)) : name
end