class Cachify::Downloader

Attributes

cache_location[R]
uri[R]

Public Class Methods

new(uri, options = {}) click to toggle source
# 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

Public Instance Methods

cache_enabled?() click to toggle source
# File lib/cachify.rb, line 40
def cache_enabled?
  !!@cache
end
cached_file() click to toggle source
# File lib/cachify.rb, line 48
def cached_file
  "#{cache_location}/#{hashed_filename_based_on_uri}"
end
cached_file_exists?() click to toggle source
# File lib/cachify.rb, line 52
def cached_file_exists?
  File.exists?(cached_file)
end
download_from_cache() click to toggle source
# 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() click to toggle source
# File lib/cachify.rb, line 26
def download_from_resource
  open(uri).read
end
get() click to toggle source
# 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() click to toggle source
# File lib/cachify.rb, line 44
def hashed_filename_based_on_uri
  Digest::MD5.hexdigest(uri)
end
initialize_cache!() click to toggle source
# 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