Fetching JSON from an external web-service - trying to refactor/tidy my code
I have a Podcast model with one attribute called :url.
A typical :url takes the following form: http://api.mixcloud.com/alivefrommaryhill/jazzcast/ and returns a JSON file
Using hashie and httparty, we can write a method (called get_json) that uses this URL to create a hash from the JSON that it links to:
class Podcast < ActiveRecord::Base
attr_accessible :url
def g开发者_开发知识库et_json
Hashie::Mash.new HTTParty.get("#{self.url}")
end
end
We can then use get_json in our views to style and display the JSON:
#/views/podcasts/index.html.haml
- for podcast in @podcasts
= link_to podcast.get_json.name, podcast_path(podcast)
= podcast.get_json.description
= image_tag podcast.get_json.pictures.medium
As you can see, each podcast calls get_json three times. I've got 21 podcasts and don't want to call this method more than once per visit since it connects to an external web-service which is very time-consuming. How can I minimize the number of times this method is called and speed things up?
Perhaps I should be doing more in my controller instead of calling the method from my view?
def index
@podcasts = Podcast.all
end
Any help appreciated
Well, the easiest fix for now would be to save the result of podcast.get_json in a local variable. That'd cut it down to once per podcast.
If you want to further reduce the number of calls, you'd have to figure a way to batch all your requests. I don't know if that site's API will let you do that.
精彩评论