Derived class for Ruby Thread?
I think that this is really a question about domain modeling.
There would be nothing wrong with what you are doing if you want to extend / enhance the way that a thread behaves - for example to add debug or performance output but I don't think that's what you want.
You probably want to model some concept in your domain with active objects. In that case the standard Ruby approach is better because it allows you to achieve this without bending your domain model.
Inheritance really should only be used to model IS_A relationships. The standard ruby code for this neatly wraps up the solution.
To make your object active, have it capture the newly created thread in some method
Class MyClass... def run while work_to_be_done do some_work end end...endthreads = []# start creating active objects by creating an object and assigning# a thread to eachthreads << Thread.new { MyClass.new.run }threads << Thread.new { MyOtherClass.new.run }... do more stuff# now we're done just wait for all objects to finish ....threads.each { |t| t.join }# ok, everyone is done, see starships on fire off the shoulder of etc# time to die ...
That's perfectly fine, I've seen people do that before. Here's some example code from one of the Ruby mailing lists that runs when Thread.new is called:
class MyThread < Thread def initialize super("purple monkey dishwasher") {|str| puts "She said, '#{str}.'"} endend
If you plan on calling Thread.fork or Thread.start to run your thread, you should be aware of this from the Ruby documentation those methods:
"Basically the same as Thread::new. However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass’s initialize method."
I prefer doing the encapsulation thus:
class Threader def initialize @thread = Thread.new(&method(:thread)) endprivate def thread # Do thready things... endend
You could also do this directly to a Thread subclass:
class ThreadyThread < Thread def initialize super(&method(:thread)) endprivate def thread # Do thready things... endend