Skip to content

Instantly share code, notes, and snippets.

@volontarian
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volontarian/702a04bd17228af082b6 to your computer and use it in GitHub Desktop.
Save volontarian/702a04bd17228af082b6 to your computer and use it in GitHub Desktop.
Wrapper of Ruby gem lastfm for tolerant requests with 3 tries used at http://volontari.at/music
class MusicArtist < ActiveRecord::Base
include LastfmRequest
end
lastfm = Lastfm.new(LastfmApiKey, LastfmApiSecret)
# Simplest option
lastfm_artist = artist.lastfm_request(lastfm, :artist, :get_info, 'The artist you supplied could not be found', artist: 'Dummy')
# Option raise_if_response_is_just_nil
begin
lastfm_artist_tags = lastfm_request(
lastfm, :artist, :get_top_tags, 'The artist you supplied could not be found', artist: 'Dummy', raise_if_response_is_just_nil: true
)
rescue StandardError => e
if e.message.match('last.fm response is just nil without exceptions')
# your exception handling code here
else
raise e
end
end
# Option raise_parse_exception
begin
lastfm_albums = MusicArtist.lastfm_request_class_method(
lastfm, :user, :get_top_albums, nil, user: 'Dummy', period: '12month', page: 1, raise_parse_exception: true
)
rescue REXML::ParseException
# your exception handling code here
end
module LastfmRequest
def self.included(base)
base.extend ClassMethods
end
def lastfm_request(lastfm, resource, method, error_message_reqexp, params = {})
self.class.lastfm_request_class_method(lastfm, resource, method, error_message_reqexp, params)
end
module ClassMethods
def lastfm_request_class_method(lastfm, resource, method, error_message_reqexp, params = {})
response = nil
raise_if_response_is_just_nil = params.delete(:raise_if_response_is_just_nil)
raise_parse_exception = params.delete(:raise_parse_exception)
i = 1
3.times do
begin
response = lastfm.send(resource).send(method, params)
raise 'last.fm response is just nil without exceptions' if response.nil? && raise_if_response_is_just_nil
break
rescue Timeout::Error, EOFError => e
puts "lastfm: #{e.class.name} for ##{i} time"
sleep 60
rescue ArgumentError => e
if e.message.match('File does not exist')
puts "lastfm: 'File does not exist' sleep 60 seconds for ##{i} time ..."
sleep 60
else
raise e
end
rescue Lastfm::ApiError => e
if error_message_reqexp.nil? || e.message.match(error_message_reqexp).nil?
if e.message.match(/Operation failed - Something else went wrong/)
puts "lastfm: operation failed - something else went wrong for ##{i} time ..."
sleep 60
else
raise e
end
end
rescue REXML::ParseException => e
raise e if raise_parse_exception
end
i += 1
end
response
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment