2016-04-23 6 views
0

私はLast.fmのサードパーティのWebアプリケーションを作成していますが、特定のアーティストに関する情報を得ることに問題があります。Railsで別のウェブサイトのサブページを解析するにはどうすればよいですか?

私はJSONからいくつかの#{アーティスト}に関するデータを解析する方法があります:私は変更する場合

artists_helper.rb

require 'net/http' 
require 'json' 

module ArtistsHelper 

def about(artist) 
    artist = "?" 
    url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json" 
    uri = URI(url) 
    response = Net::HTTP.get(uri) 
    JSON.parse(response) 
end 

end 

を '?'そのメソッドのアーティスト名には、そのアーティストのJSONファイルからアーティストに関する情報を正常に解析できます。しかし、私がページに行くときのために。 http://localhost:3000/artists/Wild+Nothing「Wild + Nothing」の値を取得し、Last.fmのJSONファイルからWild Nothingのデータを解析するには、「about(artist)」メソッドが必要です。

「約」という方法を教えてもらうにはどうすればよいですかhttp://localhost:3000/artists/は必須値ですか?ルートで

答えて

0

、アーティストコントローラで変数

get 'artists/:name', to: 'artists#about' 

を受け入れGETルート名を持つ、およそ機能を持っている:

def about 
    artist = params[:name] 
    url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json" 
    uri = URI(url) 
    response = Net::HTTP.get(uri) 
    response = JSON.parse(response) 

    render json: response 
end 

、我々は表示するために行ってもいいですjsonをビューに表示します。

ヘルパーにparamが必要な場合は、パラメータとしてヘルパーにparams[:name]を渡すだけです。

about(param[:name]) #wherever you are calling this method in the controller or view 

def about(artist) 
    url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json" 
    uri = URI(url) 
    response = Net::HTTP.get(uri) 
    JSON.parse(response) 
end 
+0

これは機能しました。ありがとう。 – staniel

関連する問題