From: Eli Bendersky Date: 2006-05-07T05:21:11+09:00 Subject: Re: Creating sub-classes using Struct Logan Capaldo wrote: > On May 6, 2006, at 2:55 PM, Eli Bendersky wrote: > >>> arbitrary classes and not just Object. Btw, if feels a bit strange to >> to do. Simplifying: >> >> I have a flat-file full of records. The way records are stored can be >> customized via a separate configuration file. I want to have a class >> Database which is a container of Record classes. The Record is best >> implemented as a Struct, IMHO, and I want to create the class >> dynamically after reading the configuration (which says which fields >> there are in a Record). I think it would be convenient for a Record to >> be a subclass of Database, since there is no point having Records >> without a Database. >> > > Eh, I'm not sure you get the is-a relationship. Saying that a Record > is a subclass of Database implies that anywhere you would use a > Database you could use a Record instead. That doesn't really make > sense. It would also seem to imply that a Record could contain many > records. Instead of > > class Database > ... > end > > class Record < Database > ... > end It seems that I managed to completely confuse everyone using an inaccurate description. By sub-class I meant a nested class here, not a child in is-a inheritence. I don't know what I was thinking :-) > > > I would suggest > > class Database > def self.new(file_containing_info) > fields = parse_field_format(file_containing_info) > Database.const_set('Record", Struct.new(*fields)) > super > end Excellent ! const_set is what I was missing to get my solution working. No more "dynamic constant assignment" errors for me :-) > > def initialize(file) > @records = [] > read_each_record_in_file(file) do |record_data| > record = Database::Record.new > extract_record_data_into(record_data, record) > @records << record > end > end > end This looks like what I need. Many thanks -- Posted via http://www.ruby-forum.com/.