From: Eric Hodel Date: 2006-04-10T15:04:51+09:00 Subject: Re: ObjectSpace searching On Apr 9, 2006, at 8:06 PM, Mark Alexander Friedgan wrote: > I wrote some code that searches ObjectSpace prior to initializing an > object to see if one of that type and some attributes is already > present and uses that instead of initializing. (yes it's active record > and i am trying to avoid stale object errors). How horrible is this? I > am searching by specific class name so in practice it ends up looking > at at most a couple of instances but is there something inherently > wrong with doing this? > > def find_in_space(search_id, search_version = nil) > retval = nil > ObjectSpace.each(Person){|person| > retval = person if (p.id == search_id) && > search_version && > p.lock_version == search_version > } > return retval || Person.find(search_id) > end For one, you could fail early: s = 'foo' obj = nil ObjectSpace.each_object(String) { |str| if str.equal? s then obj = str; break; end } p obj # => 'foo' Really, you should handle errors properly. This code won't eliminate the possibility of a double-update, another process can cause them to happen after this code gets run. (Also, you should use cached_model and turn on its local cache. Much more efficient than traversing ObjectSpace.) -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com