From 424906bafff8b2ee86370d0a33ac48992b892e65 Mon Sep 17 00:00:00 2001 From: Hipster Hitman Date: Sun, 10 Apr 2011 10:17:06 +0400 Subject: [PATCH] search autocomplete --- app/controllers/artist_controller.rb | 15 +++++++++++++++ app/models/artist.rb | 13 ++++++++++++- app/views/main/index.html.erb | 14 ++++++++++++++ config/routes.rb | 3 ++- public/stylesheets/beathaven.css | 1 + public/stylesheets/search-autocomplete.css | 3 ++- 6 files changed, 46 insertions(+), 3 deletions(-) diff --git a/app/controllers/artist_controller.rb b/app/controllers/artist_controller.rb index c2813eb..1581ba4 100644 --- a/app/controllers/artist_controller.rb +++ b/app/controllers/artist_controller.rb @@ -9,5 +9,20 @@ class ArtistController < ApplicationController end @artist = Artist.getByName(name) end + + def autocomplete + autocomplete = Artist.getLastFmAutocomplete(params[:query]) + return render :nothing => true if autocomplete.nil? + suggestions = [] + pp autocomplete["response"] + autocomplete["response"]["docs"].each do |doc| + suggestions << doc["artist"] unless suggestions.include?(doc["artist"]) + end + + render :json => { + :query => params[:query], + :suggestions => suggestions + } + end end diff --git a/app/models/artist.rb b/app/models/artist.rb index 9fc8143..ba3292e 100644 --- a/app/models/artist.rb +++ b/app/models/artist.rb @@ -1,8 +1,19 @@ class Artist < ActiveRecord::Base set_table_name 'musicbrainz.bh_artist' has_many :albums, :conditions => "release_type = 1", :order => 'year ASC, id ASC' - + def self.getByName(name) Artist.first(:conditions => ['name = ? AND id=credit_id', name], :order => 'rating DESC') end + + def self.getLastFmAutocomplete(query) + return nil if query.nil? or query.strip.empty? + + json = ActiveSupport::JSON.decode(open( + 'http://www.last.fm/search/autocomplete' << + '?q=' << URI.escape(query) + ).read) + return nil if json.empty? else return json + end end + diff --git a/app/views/main/index.html.erb b/app/views/main/index.html.erb index 3eb1856..2acb3cf 100644 --- a/app/views/main/index.html.erb +++ b/app/views/main/index.html.erb @@ -1,3 +1,17 @@ + +