From: walter@... Date: 2004-07-03T05:02:51+09:00 Subject: Re: define_method to add a Class method? > On Friday 02 July 2004 12:42, walter@mwsewall.com wrote: > > How do you use define_method (or an equivalent) to add a method to a > > Class. > > > > I want to create a class from a Database result set at runtime. I > > was doing this by building a string and the evaling it, which works, > > but wasn't all that rubyish and was ugly. > > > > I am now using an Anonymous class ie Class.new{...} and everything > > is great except I can't seem to create a class method this way. > > > > I know I am missing something quite obvious, I just can't seem to > > find it. > > > > Any pointers would be greatly appreciated. > > I'd stick with eval; it does the job. Something like this should work > just fine: > > class_name = "MyClass" > code = "print 'Hello, world!\n'" > method_name = "my_method" > > eval_string = <<-EVAL > class #{class_name} > def #{method_name} > #{code} > end > end > EVAL > > eval eval_string > > o = MyClass.new > o.my_method #=> "Hello, world!\n" > > > Sean O'Dell > That was how original version worked, and I can seem to port everything except the creation of the class methods using the Class.new{...} syntax. It just seems as if I am missing something. Can we not add a class method using define_method. I have tried it in combination with instance_eval, module_eval, directly on the class, within the class, etc but so far no luck. I guess I just want to know if it can be done using a define_ method or do we _have_ to use eval to add a class method this way. Thanks, Walt ***************************************************** Walter Szewelanczyk IS Director M.W. Sewall & CO. email : walter@mwsewall.com 259 Front St. Phone : (207) 442-7994 x 128 Bath, ME 04530 Fax : (207) 443-6284 *****************************************************