Class: Jsearch::Cache

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

Overview

Cache manager

Constant Summary collapse

BASE_DIR =
"#{Dir.home}/.cache/jsearch".freeze

Class Method Summary collapse

Class Method Details

.checkObject



14
15
16
17
18
# File 'lib/jsearch/cache.rb', line 14

def self.check
  return if Dir.exist?(BASE_DIR)

  FileUtils.mkdir_p(BASE_DIR)
end

.clearObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/jsearch/cache.rb', line 49

def self.clear
  found_files, found_dirs = files.partition do |path|
    File.file?(path)
  end

  files_total = found_files.reduce(0) do |total, path|
    puts path
    total += File.size(path)
    File.unlink(path)
    total
  end

  found_dirs.sort.reverse.each do |dir|
    FileUtils.rmdir(dir)
  end

  files_total
end

.filesObject



45
46
47
# File 'lib/jsearch/cache.rb', line 45

def self.files
  Dir.glob("#{BASE_DIR}/**/*")
end

.get(url) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/jsearch/cache.rb', line 29

def self.get(url)
  check

  file = path(url)
  return { contents: File.read(file), cache: true } if File.exist?(file)

  contents = URI.parse(url).open.read
  dir      = File.dirname(file)
  FileUtils.mkdir_p(dir)
  File.write(file, contents)

  { contents: contents, cache: false }
rescue StandardError => e
  $stderr.puts "Error downloading: #{e}"
end

.path(url) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/jsearch/cache.rb', line 20

def self.path(url)
  tokens = url.sub(Configuration.instance.base, "").split("/")
  dir    = tokens[1..-2].join("/")
  file   = tokens.last
  sep    = dir.empty? ? "" : "/"

  "#{BASE_DIR}/#{dir}#{sep}#{file}"
end

.sizeObject



68
69
70
71
72
73
74
75
# File 'lib/jsearch/cache.rb', line 68

def self.size
  files.reduce(0) do |total, file|
    next total unless File.file?(file)

    total += File.size(file)
    total
  end
end