1
0
Fork 0
musicbrainz/lib/musicbrainz/client_modules/caching_proxy.rb

48 lines
1.1 KiB
Ruby
Raw Normal View History

# -*- encoding : utf-8 -*-
2012-10-12 12:45:51 +00:00
module MusicBrainz
module ClientModules
module CachingProxy
def cache_path
MusicBrainz.config.cache_path
end
def clear_cache
FileUtils.rm_r(cache_path) if cache_path && File.exist?(cache_path)
end
def get_contents(url)
2013-01-20 12:36:52 +00:00
return super unless caching?
2012-10-12 12:45:51 +00:00
2013-01-20 12:36:52 +00:00
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
2012-10-12 12:45:51 +00:00
2013-01-20 12:36:52 +00:00
response = { body: nil, status: 500 }
2012-10-12 12:45:51 +00:00
if File.exist?(file_path)
2013-01-20 12:36:52 +00:00
response = {
body: File.open(file_path, 'rb').gets,
status: 200
}
2012-10-12 12:45:51 +00:00
else
response = super
2013-01-20 12:36:52 +00:00
if response[:status] == 200
FileUtils.mkpath(dir_path)
File.open(file_path, 'wb') do |f|
2013-01-20 12:36:52 +00:00
f.puts(response[:body])
f.chmod(0755)
2012-10-12 12:45:51 +00:00
f.close
end
end
end
response
end
2013-01-20 12:36:52 +00:00
def caching?
MusicBrainz.config.perform_caching
end
2012-10-12 12:45:51 +00:00
end
end
end