Forum: Ruby on Rails Temporary Model Data

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
John S. (Guest)
on 2006-03-17 20:28
(Received via mailing list)
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
Noel R. Morais (Guest)
on 2006-03-17 21:21
(Received via mailing list)
try this:

 def invitations
     if @@invitations.nil?
       @@invitations = all_pgm_updates.find_all do |update|
         update.invited?
       end
     end
     @@invitations
   end
Trevor S. (Guest)
on 2006-03-17 21:52
(Received via mailing list)
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
This topic is locked and can not be replied to.