Question

I am cross referencing my users' Facebook friends with user's signed up with my site. Don't ask me why I did it this way, but I have a piece of code that I want to basically run once and then "cache" so that it doesn't have to cross reference every time the page loads.

if defined? @friends
  p "did NOT have to reload"
  @friends
else
  p "had to reload"
  @friends = FbGraph::User.me(current_user.oauth_token).friends
  @friends.map! do |friend|
    friend if User.find_by_uid(friend.identifier) != nil
  end
  @friends.compact!
end

Say this loads every time the friends_list action is loaded. Why does it continually have to reload @friends?

Was it helpful?

Solution

@friends is just an instance variable that gets created then destroyed with every request.

Your best bet is to cache the response like so:

@friends = Rails.cache.fetch("friends-#{current_user.cache_key}") do
  friends = FbGraph::User.me(current_user.oauth_token).friends
  friends.map! do |friend|
    friend if User.find_by_uid(friend.identifier) != nil
  end
  friends.compact!
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top