Class: Cachify::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/cachify.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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, options = {})
  @uri = uri
  @cache = options.fetch(:cache) { true }
  @cache_location = options[:cache_location] || "#{Dir.tmpdir}/cachify"
  initialize_cache!
end

Instance Attribute Details

#cache_locationObject (readonly)

Returns the value of attribute cache_location.



10
11
12
# File 'lib/cachify.rb', line 10

def cache_location
  @cache_location
end

#uriObject (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

Returns:

  • (Boolean)


40
41
42
# File 'lib/cachify.rb', line 40

def cache_enabled?
  !!@cache
end

#cached_fileObject



48
49
50
# File 'lib/cachify.rb', line 48

def cached_file
  "#{cache_location}/#{hashed_filename_based_on_uri}"
end

#cached_file_exists?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/cachify.rb', line 52

def cached_file_exists?
  File.exists?(cached_file)
end

#download_from_cacheObject



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_resourceObject



26
27
28
# File 'lib/cachify.rb', line 26

def download_from_resource
  open(uri).read
end

#getObject



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_uriObject



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