From: Steve Midgley Date: 2007-02-15T05:59:15+09:00 Subject: Re: Creating a second instance of a singleton class? I love this group b/c there are so many clever people here. Ara - you're definitely getting me close. I'll open the bag a little at the expense of brevity so you can see what I'm trying to accomplish. I'm using Rails v1.2.2, and in particular ActiveRecord 1.15.2. In the course of a data operation, I have a series of active record instances: instance1ofclass1, instance2ofclass1, instance1ofclass2, instance2ofclass2, etc..] For any given activerecord class for the above list (let's use an example table called "property") there is an identical table (less the primary key) called "property_versions" I would like to be able to create a new instance of the activerecord model but using a new table name - changing the table_name is handled as a class method "set_table_name(new_name)" So I could say: #==> assumes we have a "property" instance available.. orig_table = Property.table_name class Property set_table_name 'property_versions' end prop_versions = Property.new(property.attributes) class Property set_table_name orig_table end But this doesn't seem threadsafe - I could block the whole operation but (at the time) it seemed cleaner and simpler to just modify the instance of the class rather than the whole parent class. I may just be an idiot and there's a way easier way to handle this. But this was supposed to be a quick little function. Isn't working out like that though. :) Thanks again for any insight, Steve ara.t.howard wrote: > > harp:~ > cat a.rb > > require 'rubygems' > > require 'prototype' > > > > # 1) > > class Test; end > > > > # 2) > > test1 = Test.new > > > > # 3,4) > > Test2 = Class.new(test1.class){ > > def new_method > > p 'no singleton class is needed' > > end > > } > > > > # 5) > > test2 = Test2.new > > > > test2.new_method > > > > > > harp:~ > ruby a.rb > > "no singleton class is needed" > >and, if it is > > harp:~ > cat a.rb > require 'rubygems' > require 'prototype' > > # 1) > class Test; end > > # 2) > test1 = Test.new > > # 3) > m = Module.new{ > def new_method > p 'if a singleton class is needed' > end > } > (class << test1; self; end).module_eval{ include m } > > # much easier - no singleton class needed here either > # test1.extend m > > # 4) > Test2 = Class.new(test1.class){ include m } > > # 5) > test2 = Test2.new > > test2.new_method > > > harp:~ > ruby a.rb > "if a singleton class is needed"