Class: CyberarmEngine::Cache::DownloadManager
- Inherits:
-
Object
- Object
- CyberarmEngine::Cache::DownloadManager
- Defined in:
- lib/cyberarm_engine/cache/download_manager.rb
Defined Under Namespace
Classes: Download
Instance Attribute Summary collapse
-
#downloads ⇒ Object
readonly
Returns the value of attribute downloads.
Instance Method Summary collapse
- #active_downloads ⇒ Object
- #download(url:, save_as: nil, &callback) ⇒ Object
-
#initialize(max_parallel_downloads: 4) ⇒ DownloadManager
constructor
A new instance of DownloadManager.
- #progress ⇒ Object
- #prune ⇒ Object
- #status ⇒ Object
- #update ⇒ Object
Constructor Details
#initialize(max_parallel_downloads: 4) ⇒ DownloadManager
Returns a new instance of DownloadManager.
6 7 8 9 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 6 def initialize(max_parallel_downloads: 4) @max_parallel_downloads = max_parallel_downloads @downloads = [] end |
Instance Attribute Details
#downloads ⇒ Object (readonly)
Returns the value of attribute downloads.
4 5 6 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 4 def downloads @downloads end |
Instance Method Details
#active_downloads ⇒ Object
36 37 38 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 36 def active_downloads @downloads.select { |d| %i[pending downloading].include?(d.status) } end |
#download(url:, save_as: nil, &callback) ⇒ Object
11 12 13 14 15 16 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 11 def download(url:, save_as: nil, &callback) uri = URI(url) save_as ||= "filename_path" # TODO: if no save_as path is provided, then get one from the Cache controller @downloads << Download.new(uri: uri, save_as: save_as, callback: callback) end |
#progress ⇒ Object
26 27 28 29 30 31 32 33 34 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 26 def progress remaining_bytes = @downloads.map { |d| d.remaining_bytes }.sum total_bytes = @downloads.map { |d| d.total_bytes }.sum v = 1.0 - (remaining_bytes.to_f / total_bytes) return 0.0 if v.nan? v end |
#prune ⇒ Object
49 50 51 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 49 def prune @downloads.delete_if { |d| d.status == :finished || d.status == :failed } end |
#status ⇒ Object
18 19 20 21 22 23 24 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 18 def status if active_downloads > 0 :busy else :idle end end |
#update ⇒ Object
40 41 42 43 44 45 46 47 |
# File 'lib/cyberarm_engine/cache/download_manager.rb', line 40 def update @downloads.each do |download| if download.status == :pending && active_downloads.size <= @max_parallel_downloads download.status = :downloading Thread.start { download.download } end end end |