memcache for variables

hey,

for performance reasons i want to cache (template) variables using memcache, making access to data easy in templates by using a simple syntax like <%=users(2).name%>. this actually should tell the view to load the field 'name' from the model/table 'users' with id=2. it first tries memcache and if not found, loads the data from the and stores it in memcache.

has anyone done this before, any ready to use plugins available? :). if not, any ideas/suggestions on how to implement this best in ror?

caching partials or whole actions is not an option because of too complex dependencies.

thanks

in your config/environment/development.rb file (or whatever environement your are configuring)

config.cache_store = :mem_cache_store

Depending on how much memory you want to consume you can either load your whole user model, the name to ID collection or just the users that log in.

In the User model do something like:

def self.names   Rails.cache.fetch('user_names', :expires_in => 3600) {User.all.collect {|u| [u.id,u.name]}} # names are cached for 1hr (3600 seconds) end

again in your controller:

def list   @names ||= User.names.sort end

in your view: <% @names.each do |name| -%>   <%= name[0] -%><br /> <% end -%>

If the names aren't cached or the cache is older than the one hour defined in the model then the fetch method knows to go grab them afresh.

I'm using memcache in a more complex manner with full objects and it works like a charm - as a matter of fact this has taken common requests for fetching data completely off of the database. I rebuild the cache without using expiration by implementing callbacks on modification of the underlying data - this has taken load times for data intensive / cmplex data sets from 20+ seconds down to an imperceivable delay... makes clients happy to see that kind of improvement. :slight_smile:

Naturally you will need to have the memcache service running somewhere in your environment. Hope that helps Ben

Except in the collection you actually would put [u.name,u.id]