From: Brian Takita Date: 2005-12-15T16:52:17+09:00 Subject: Re: Dynamically adding methods to a Ruby class ------=_Part_1404_14770385.1134633131166 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline Hello John, This isn't quite as cool as a prototype, but here is another possible type of solution: class Dynamic attr_reader :dynamic_methods def initialize @dynamic_methods =3D Hash.new end alias alias_method_missing method_missing def method_missing(name, *args) unless @dynamic_methods.include?(name) alias_method_missing(name, *args) return end @dynamic_methods[name].call(*args) end end d =3D Dynamic.new # You can also use Proc.new instead of lambda d.dynamic_methods[:test] =3D lambda do |*args| puts 'test ' + args.to_s end d.test(1, 2) # test 12 Of course you could add the method that you describe in your link: d.dynamic_methods[:Count] =3D lambda do |*args| create_ruby_instance_method(self.class, 'Count') do include 'System.Collections' ldarg_2 call 'static Marshal::ToClrObject(VALUE)' call 'ArrayList::get_Count()' call 'static Marshal::ToRubyNumber(Int32)' ret end self.Count end -- Brian Takita http://freeopinion.org On 12/14/05, Eero Saynatkari wrote: > > John Lam wrote: > > I just finished writing the first spike for my Ruby CLR bridge tonight, > > and > > I'm wondering if there might be a better (or more efficient) way to add > > instance methods to a class object than this: > > > > class Module > > def const_missing(symbol) > > obj =3D Class.new > > obj.class_eval %{ > > def initialize > > ... > > end > > > > def method_missing(name, *params) > > ... > > end > > } > > const_set(symbol, obj) > > end > > end > > Not really, except for using define_method (which has > some limitations that would probably make it unsuitable > for a #method_missing implementation). The 'Class methods' > thread had pretty much this exact implementation.. > > Perhaps some sort of a prototype-based approach? > > > Thanks, > > -John > > http://www.iunknown.com > > > > PS If you're wondering what the code in the ... blocks do, read my > > write-up > > of this code at: > > http://www.iunknown.com/articles/2005/12/14/hello-rubyclr > > > E > > -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_1404_14770385.1134633131166--