On Mon, 2004-08-16 at 15:23, Daniel Cremer wrote:
> ... What I don't understand is how would you
> implement object pools in Ruby ? If I understand correctly with object
> pools you often have data representing state stored separately. Then
> when needed you can grab an instance of the object from the pool and
> populate it with this data.
> For an example like that I would like to have a base-class that
> implements a persist() method. This way developers working on a class
> can inherit this class and simply pass the objects representing state to
> this persist() method.
>
> def persist(*state_objs)
> ...
> persistent_objects = Array.new()
> state_objs.each { |obj| persistent_objects << obj }
> ...
> end
>
> >From then on it could be included into object pools with no further work
> from the developer.
>
> But this is were I have problems. Implementing this in the base class
> such that it can take any list of variables without any knowledge of
> their names and being able to get back to the contents of the variables
> to store the state before returning the object to the pool.
> I hope this makes sense, I might be confusing myself
Ok I think I cleared my brain a bit on my particular example and did a
quick implementation:
--------------------------------
require 'set'
class MyBaseClass
@@persist = Set.new()
def MyBaseClass.persist(*symbol)
symbol.each do |symbol|
instance_symbol = "@" + symbol.to_s
@@persist.add(instance_symbol)
end
end
def return_persistent_vars()
output = Array.new()
@@persist.each {|val| output << self.instance_variable_get(val) }
return output
end
end
class ObjPoolObj < MyBaseClass
attr_accessor :var1, :var2, :var3
persist :var1, :var2
def initialize
@var1 = "hello"
@var2 = "world"
@var3 = "nothingHere"
end
end
test_obj = ObjPoolObj.new()
puts test_obj.return_persistent_vars() #=> hello
#=> world
test_obj.var1 = "hellomodified"
puts test_obj.return_persistent_vars() #=> hellomodified
#=> world
---------------------------
The part I find cool is being able to call: "persist :var1, :var2" in
the same manner as attr_accessor. Of course the whole storing of the
data and stuffing it back into the object from the pool would need to be
implemented but that should be simple enough. I'll think about
generalising this stuff...
thanks for keeping my neurons firing.
Daniel