Skip to content

Instantly share code, notes, and snippets.

@thisredone
Created August 24, 2012 12:38
Show Gist options
  • Save thisredone/3450103 to your computer and use it in GitHub Desktop.
Save thisredone/3450103 to your computer and use it in GitHub Desktop.
multitag search for last.fm (cached)
require 'lastfm'
api_key ||= 'xxx'
api_secret ||= 'xxx'
$lastfm ||= Lastfm.new(api_key, api_secret)
# token = lastfm.auth.get_token
# lastfm.session = lastfm.auth.get_session(:token => token)['key']
$cache ||= {}
def multitag *tags
artists = tags.map do |tag|
print '.'
results = $cache[tag] ||= $lastfm.tag.get_top_artists(:tag => tag, :limit => 9999)
Hash[tag, results]
end.compact.inject(&:merge)
print '.'
matches = artists.map { |_, a| a.map { |x| x['name'] } }.inject(&:&)
puts '.'
matches = matches.map do |a|
[a, artists.map { |tag, as| [tag, as.find { |x| x['name'] == a }['rank']] } ]
end.sort { |x| x.map{|y|y[1].map{|z|z[1].to_i}.inject(&:+)}.inject(&:<=>) }
matches.empty? ? raise : matches
rescue
puts 'No matches'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment