Temporary Model Data


#1

I am trying to optimize some methods in my model so they don’t repeat
CPU intensive algorithms every time I call the method in the same
request/response cycle.
Eg.

def invitations
all_pgm_updates.find_all do |update|
update.invited?
end
end

I want to do something like:

def invitations
if @invitations.nil?
@invitations = all_pgm_updates.find_all do |update|
update.invited?
end
end
@invitations
end

but isn’t the instance variable, @invitations, going to stick around
as long as the record is stored in the session? How do I clear it at
the beginning of every request? Models don’t have access to flash, I
don’t think, so I need an alternative.

-John


John S.
Computing Staff - Webmaster
Kavli Institute for Theoretical Physics
University of California, Santa Barbara
removed_email_address@domain.invalid
(805) 893-6307


#2

try this:

def invitations
if @@invitations.nil?
@@invitations = all_pgm_updates.find_all do |update|
update.invited?
end
end
@@invitations
end


#3

Hi John,

So, you’re storing the model instance in the session right? And it’s
in that model that you want to cache the expensive data, but you
don’t want the cache to persist between HTTP requests?

The solution is pretty simple: don’t store the model instance in the
session. Store the model’s ID instead.

in controller:

before_filter :get_my_model, :only => [:some_action]

def get_my_model
if session[:mymodel_id]
@mymodel = MyModel.find(session[:mymodel_id])
end
end

def some_action
@mymodel.invitations #builds the model’s @invitations cache
@mymodel.invitations #uses the cached @invitations
end

Hope that helps,
Trevor

Trevor S.
http://somethinglearned.com