From: Markus Date: 2004-09-19T14:03:41+09:00 Subject: Re: bug bytes On Sat, 2004-09-18 at 21:05, Bill Guindon wrote: > I'm still hating the 'pack' > statement, so I refuse to apologise to it ;) I suppose writing a wrapper of some sort doesn't work for you? For example, when I had to read & write some Pascal records (native format binary goo) I wrote a little thing that I stuck in "module Module" (IIRC) to define the fields, and get_record and put_record methods that schleped the data to/from the format, and forgot about the internals as quickly as I could. A quick check just now failed to turn up the code, but I can sketch it. ********************************************************************* ** WARNING: THE FOLLOWING CODE HAS BEEN TYPED FROM MEMORY BY SOMEONE ** WHO SHOULD HAVE GONE TO BED SEVERAL HOURS AGO. ********************************************************************* * Add something that looks something like $packing_formats = { :integer => 'i', :real => 'f', --etc, to suit } class Module # # To automate the reading and writing of objects # def columns @columns ||= [] end def pack_format @pack_format ||= '' end private def field(id,type) @columns ||= [] id = id.to_s attr_accessor id unless instances_respond_to? id+'=' @columns << id @pack_format = pack_format + $packing_formats[type] end end * then define a pack/unpack methods something like class Object def pack self.class.fields.collect { |field| self.send(field) }.pack(self.class.pack_format) end def unpack(s) v = s.unpack(self.class.pack_format) self.class.fields.each { |field| self.send(field+'=',v.shift) } end end * look into the pen with the bright red light and forget about how it works. Use "field" instead of "attr_accessor" when defining objects that need to match external record formats IIRC, the version I wrote for myself wound up having another level of abstraction that made it look like an SQL-based object persistence interface that was in use in the same program. Then as the data storage back-end got cleaned up it shriveled up and eventually blew away. -- MarkusQ