我有一个练习,其中我必须使用HTTParty来使用API来显示有关电影的更多信息。当标题电影中有两个或两个以上的单词时,所有内容都会崩溃,因为每个单词之间都添加了“%20”。
使用API的方法是否比以前更好?我认为我的解决方案不是很完善。我的解决方案基于GoRails情节之一。
信息应来自API,我无法将此数据存储在数据库中。 API的输出如下:
{"data":{"id":"5","type":"movie","attributes":{"title":"Inglourious
Basterds","description":"In Nazi-occupied France during World War II, a
plan to assassinate Nazi leaders by a group of Jewish U.S. soldiers
coincides with a theatre owner's vengeful plans for the
same.","rank":8.3,"poster":"/inglourious_basterds.jpg"}}}
movie_details.rb
class MovieDetails
include HTTParty
base_uri "https://fakeaddress-api.com/api/v1/movies"
def self.title(title)
get("/#{title}.json").parsed_response["data"]["attributes"]["title"]
end
def self.description(title)
get("/#{title}.json").parsed_response["data"]["attributes"]["description"]
end
def self.poster(title)
get("/#{title}.json").parsed_response["data"]["attributes"]["poster"]
end
def self.rank(title)
get("/#{title}.json").parsed_response["data"]["attributes"]["rank"]
end
end
movies_controller.rb
def show
@movie = Movie.find(params[:id])
@description = MovieDetails.description(@movie.title.split.join(""))
@rank = MovieDetails.rank(@movie.title.split.join(""))
@poster = MovieDetails.poster(@movie.title.split.join(""))
end
标题中有两个词时,链接为:https://fakeaddress-api.com/api/v1/movies/Inglourious%20Basterds-用于电影《无耻混蛋》。