Module: Eaternet::Util
- Defined in:
- lib/eaternet/util.rb
Class Method Summary collapse
-
.download(source:, dest:) ⇒ File
Download a file from the network.
-
.download_and_cache(source:, dest:) ⇒ File
Download a file from the network, using a 12-hour cache.
-
.download_and_extract_zipfile(url) ⇒ String
Download a zip file and extract it into a temp directory.
- .expired?(cache_path) ⇒ Boolean
-
.extract_zipfile(path:, dest_dir:) ⇒ Object
Extract a Zip archive.
- .file_age_in_days(path) ⇒ Float
- .generate_cache_path(url) ⇒ Object
- .prepare_cache_dir ⇒ Object
Class Method Details
.download(source:, dest:) ⇒ File
Download a file from the network.
37 38 39 40 41 |
# File 'lib/eaternet/util.rb', line 37 def self.download(source:, dest:) File.open(dest, 'wb') do |file| file << HTTParty.get(source, verify: false).body end end |
.download_and_cache(source:, dest:) ⇒ File
Download a file from the network, using a 12-hour cache.
25 26 27 28 29 30 |
# File 'lib/eaternet/util.rb', line 25 def self.download_and_cache(source:, dest:) cache_path = generate_cache_path(source) download(source: source, dest: cache_path) if expired? cache_path FileUtils.cp cache_path, dest File.open dest end |
.download_and_extract_zipfile(url) ⇒ String
Download a zip file and extract it into a temp directory.
12 13 14 15 16 17 18 |
# File 'lib/eaternet/util.rb', line 12 def self.download_and_extract_zipfile(url) dir = Dir.mktmpdir zip_path = File.join(dir, 'zip-file.zip') download_and_cache(source: url, dest: zip_path) extract_zipfile(path: zip_path, dest_dir: dir) dir end |
.expired?(cache_path) ⇒ Boolean
65 66 67 |
# File 'lib/eaternet/util.rb', line 65 def self.expired?(cache_path) !File.exist?(cache_path) || file_age_in_days(cache_path) > 0.5 end |
.extract_zipfile(path:, dest_dir:) ⇒ Object
Extract a Zip archive.
49 50 51 52 53 54 55 56 57 58 |
# File 'lib/eaternet/util.rb', line 49 def self.extract_zipfile(path:, dest_dir:) open(path) do |zip_file| Zip::File.open(zip_file, 'rb') do |zip_data| zip_data.each do |entry| dest_path = File.join(dest_dir, entry.name) entry.extract(dest_path) end end end end |
.file_age_in_days(path) ⇒ Float
61 62 63 |
# File 'lib/eaternet/util.rb', line 61 def self.file_age_in_days(path) (Time.now - File.mtime(path)).to_i / 86_400.0 end |
.generate_cache_path(url) ⇒ Object
69 70 71 72 73 |
# File 'lib/eaternet/util.rb', line 69 def self.generate_cache_path(url) cache_dir = prepare_cache_dir cache_key = 'cache-key-' + Base64.strict_encode64(url) File.join(cache_dir, cache_key) end |
.prepare_cache_dir ⇒ Object
75 76 77 78 79 |
# File 'lib/eaternet/util.rb', line 75 def self.prepare_cache_dir cache_dir = '/tmp/eaternet' `mkdir -p #{cache_dir}` cache_dir end |