如何解析Rails中其他网站的子页面?

时间:2016-04-23 10:10:53

标签: ruby-on-rails json

我正在创建Last.fm的第三方网络应用程序,我遇到了从他们那里获取有关某位艺术家的信息的问题。

我有一个从JSON解析一些#{artist}的数据的方法:

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/之后的内容是什么值?

1 个答案:

答案 0 :(得分: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。

如果您需要帮助程序中的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