Rails move expensive method to task
I have these two methods in my model. One method looks up a single
CatalogItem facebook like count, and another that loops through all active
CatalogItems and finds their like counts using the aforementioned.
It takes a while to run through all active facebook likes...it might loop
anywhere from 300-1000 objects; so i'd like to move this to some sort of
cron, or whatever you guys suggest.
I was thinking I should add a column to CatalogItem called
cached_fb_count, and adapt self.facebook_likes to write to that colimn
whenever that task runs.
Is this the right approach? What would that task look like if it was
running every 2 hours?
def self.facebook_likes
self.active.each_with_index do |i, index|
_likes = i.facebook_like_count
puts "#{index+1} Likes: #{_likes} ########### ID: #{i.id} "
end
end
def facebook_like_count
item_like_count =
JSON.parse(open("https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url='https://www.foobar.com/catalog_items/#{self.id}'&format=json").read).first.flatten[1]
item_like_count = item_like_count + 1 if item_like_count > 0
end
No comments:
Post a Comment