2016-04-23 59 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我需要'about(artist)'方法来获取值'Wild + Nothing'并从Last.fm的JSON文件中解析Wild Nothing的数据。

如何判断http://localhost:3000/artists/是否为必填项?

回答

0

在路线,有一个接受可变

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

在艺术家控制器获取路线名字,有一个关于功能:

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在视图上。

如果你需要助手的参数,只需将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

相关问题