lib/echonest/api.rb in ruby-echonest-0.1.2 vs lib/echonest/api.rb in ruby-echonest-0.2.0
- old
+ new
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
require 'digest/md5'
require 'httpclient'
require 'json'
+require 'fileutils'
module Echonest
class Api
BASE_URL = 'http://developer.echonest.com/api/v4/'
USER_AGENT = '%s/%s' % ['ruby-echonest', ::Echonest::VERSION]
@@ -102,16 +103,26 @@
@api.request('track/upload', :post, options)
end
end
def analysis(filename)
- analysis_url = analysis_url(filename)
- Analysis.new_from_url(analysis_url)
- end
-
- def analysis_url(filename)
md5 = Digest::MD5.hexdigest(open(filename).read)
+ cache_path = DIRECTORY + 'analysis' + md5
+ if File.exists?(cache_path)
+ analysis = Analysis.new(open(cache_path).read)
+ else
+ analysis = Analysis.new_from_url(analysis_url(filename, md5))
+ cache_path.dirname.mkpath
+ open(cache_path, 'w') do |file|
+ file.write analysis.json
+ end
+ end
+
+ analysis
+ end
+
+ def analysis_url(filename, md5)
while true
begin
response = profile(:md5 => md5)
rescue Api::Error => e
if e.message =~ /^The Identifier specified does not exist/