Class: Cachify::Downloader
- Inherits:
-
Object
- Object
- Cachify::Downloader
- Defined in:
- lib/cachify.rb
Instance Attribute Summary collapse
-
#cache_location ⇒ Object
readonly
Returns the value of attribute cache_location.
-
#uri ⇒ Object
readonly
Returns the value of attribute uri.
Instance Method Summary collapse
- #cache_enabled? ⇒ Boolean
- #cached_file ⇒ Object
- #cached_file_exists? ⇒ Boolean
- #download_from_cache ⇒ Object
- #download_from_resource ⇒ Object
- #get ⇒ Object
- #hashed_filename_based_on_uri ⇒ Object
-
#initialize(uri, options = {}) ⇒ Downloader
constructor
A new instance of Downloader.
- #initialize_cache! ⇒ Object
Constructor Details
#initialize(uri, options = {}) ⇒ Downloader
Returns a new instance of Downloader.
11 12 13 14 15 16 |
# File 'lib/cachify.rb', line 11 def initialize(uri, = {}) @uri = uri @cache = .fetch(:cache) { true } @cache_location = [:cache_location] || "#{Dir.tmpdir}/cachify" initialize_cache! end |
Instance Attribute Details
#cache_location ⇒ Object (readonly)
Returns the value of attribute cache_location.
10 11 12 |
# File 'lib/cachify.rb', line 10 def cache_location @cache_location end |
#uri ⇒ Object (readonly)
Returns the value of attribute uri.
10 11 12 |
# File 'lib/cachify.rb', line 10 def uri @uri end |
Instance Method Details
#cache_enabled? ⇒ Boolean
40 41 42 |
# File 'lib/cachify.rb', line 40 def cache_enabled? !!@cache end |
#cached_file ⇒ Object
48 49 50 |
# File 'lib/cachify.rb', line 48 def cached_file "#{cache_location}/#{hashed_filename_based_on_uri}" end |
#cached_file_exists? ⇒ Boolean
52 53 54 |
# File 'lib/cachify.rb', line 52 def cached_file_exists? File.exists?(cached_file) end |
#download_from_cache ⇒ Object
30 31 32 33 34 35 36 37 38 |
# File 'lib/cachify.rb', line 30 def download_from_cache file = if cached_file_exists? open(cached_file).read else download_from_resource end File.write(cached_file, file) unless cached_file_exists? file end |
#download_from_resource ⇒ Object
26 27 28 |
# File 'lib/cachify.rb', line 26 def download_from_resource open(uri).read end |
#get ⇒ Object
18 19 20 21 22 23 24 |
# File 'lib/cachify.rb', line 18 def get if cache_enabled? download_from_cache else download_from_resource end end |
#hashed_filename_based_on_uri ⇒ Object
44 45 46 |
# File 'lib/cachify.rb', line 44 def hashed_filename_based_on_uri Digest::MD5.hexdigest(uri) end |
#initialize_cache! ⇒ Object
56 57 58 59 60 61 |
# File 'lib/cachify.rb', line 56 def initialize_cache! unless Dir.exists?(cache_location) Dir.mkdir(cache_location) FileUtils.chmod 0700, cache_location end end |