class RMD::Downloader

Attributes

options[R]

Public Class Methods

download(link, options = {}) click to toggle source
# File lib/rmd/downloader.rb, line 42
def self.download(link, options = {})
  new(link, options).download
end
new(link, options = {}) click to toggle source
# File lib/rmd/downloader.rb, line 9
def initialize(link, options = {})
  @link = link
  @options = options
end

Public Instance Methods

download() click to toggle source
# File lib/rmd/downloader.rb, line 14
def download
  puts file_name.green

  progress_bar = ProgressBar.create(
    starting_at: 0,
    total: nil,
    format: "%a %B %p%% %r KB/sec",
    rate_scale: lambda { |rate| rate / 1024 }
  )

  content_length_proc = Proc.new { |content_length|
    progress_bar.total = content_length
  }

  progress_proc = Proc.new { |bytes_transferred|
    if progress_bar.total && progress_bar.total < bytes_transferred
      progress_bar.total = nil
    end
    progress_bar.progress = bytes_transferred
  }

  open(link, "rb", content_length_proc: content_length_proc, progress_proc: progress_proc) do |page|
    File.open(file_path, "wb") do |file|
      file.write(page.read)
    end
  end
end

Private Instance Methods

file_name() click to toggle source
# File lib/rmd/downloader.rb, line 57
def file_name
  @file_name ||= uncached_file_name
end
file_path() click to toggle source
# File lib/rmd/downloader.rb, line 48
def file_path
  if folder_path
    FileUtils.mkdir_p(folder_path) unless File.directory?(folder_path)
    File.join(folder_path, file_name)
  else
    file_name
  end
end
folder_path() click to toggle source
# File lib/rmd/downloader.rb, line 71
def folder_path
  options[:folder]
end
uncached_file_name() click to toggle source
# File lib/rmd/downloader.rb, line 61
def uncached_file_name
  uri = URI.parse(link)
  name = CGI::parse(uri.query.to_s)['filename'].first
  if name
    name
  else
    File.basename(uri.path)
  end
end