Module: MusicBrainz::ClientModules::CachingProxy

Included in:
MusicBrainz::Client
Defined in:
lib/musicbrainz/client_modules/caching_proxy.rb

Instance Method Summary collapse

Instance Method Details

#cache_pathObject


5
6
7
# File 'lib/musicbrainz/client_modules/caching_proxy.rb', line 5

def cache_path
  MusicBrainz.config.cache_path
end

#caching?Boolean


42
43
44
# File 'lib/musicbrainz/client_modules/caching_proxy.rb', line 42

def caching?
  MusicBrainz.config.perform_caching
end

#clear_cacheObject


9
10
11
# File 'lib/musicbrainz/client_modules/caching_proxy.rb', line 9

def clear_cache
  FileUtils.rm_r(cache_path) if cache_path && File.exist?(cache_path)
end

#get_contents(url) ⇒ Object


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/musicbrainz/client_modules/caching_proxy.rb', line 13

def get_contents(url)
  return super unless caching?

  hash = Digest::SHA256.hexdigest(url)
  dir_path = [cache_path, *(0..2).map{ |i| hash.slice(2*i, 2) }].join(?/)
  file_path = [dir_path, '/', hash.slice(6, 58), '.xml'].join

  response = { body: nil, status: 500 }

  if File.exist?(file_path)
    response = {
      body: File.open(file_path, 'rb').gets,
      status: 200
    }
  else
    response = super
    if response[:status] == 200
      FileUtils.mkpath(dir_path)
      File.open(file_path, 'wb') do |f|
        f.puts(response[:body])
        f.chmod(0755)
        f.close
      end
    end
  end

  response
end