Calling Twitter API Caching in Rails

My project implements the OAuth Twitter Login dance and displays a page showing all the users that the current user is following.

# /views/user/show.html.erb <h1>Users You Follow</h1> <%= render :partial => 'followed_user', :collection => @current_user.following %> 

following is the virtual attribute of the Users model.

 # /users/models/user.rb def following result = twitter_request_authenticated('get_following') parse_body(result) end 

Firstly, because I'm new to Rails (and MVC), I have to ask: is this a suitable abstraction? . Should these "next users" be modeled?

And now the real question:

Hit on Twitter for this information at every page load seems unnecessary. If we wanted to cache the result of such an API call for a certain period of time (and make a method available for the convenience of clearing this cache), how can we do this? Is it just a matter of storing the return value of the API call in the database column along with the "expiry" column and only the API call when that column value is empty or cache_expires <Now? If so, it looks like it could be better in its own model. Thoughts?

+6
ruby-on-rails twitter
source share
1 answer

If you want the cache to expire after a certain time, you probably want to use Memcached. Memcached lets you specify the expiration time of your cache. After you configure Rails to use Memcached as the default cache solution, you can do the following:

 def following Rails.cache.fetch("following/#{id}", :expires_in => 1.hour) do result = twitter_request_authenticated('get_following') parse_body(result) end end 

It will cache the following list in memory for 1 hour, and the cache will be unique to each user. You could manually expire this cache at any time with this command:

 Rails.cache.delete("following/#{id}") # where id is the user id 

To get started with Ruby on Rails caching, check out this guide.

PS: I think your approach to modeling each user that matches current_user is great. If you want to complete the full set of actions for these users, it might be worth creating a separate model for TwitterUser, but I would not combine User and TwitterUser, because they are probably completely different. For example, a random TwitterUser might not have authorization on your system and probably won't be able to log in just because a user on your system is following it.

+11
source share

All Articles