"trans. (T. Onoma)" <transami / runbox.com> schrieb im Newsbeitrag news:200410011213.17426.transami / runbox.com... > On Friday 01 October 2004 03:50 am, Robert Klemme wrote: >> class Adaptor >> def initialize(obj, mappings) >> @obj = obj >> scl = class<<self; self end >> >> # delegation of all public methods >> obj.public_methods.each do |m| >> m = m.to_sym >> >> unless mappings[m] >> scl.class_eval { define_method(m) { |*a| @obj.send(m,*a) } } >> end >> end >> >> # remapping >> mappings.each do |m,mapped| >> case mapped >> when Symbol >> scl.class_eval { define_method(m) {|*a| >> @obj.send(mapped,*a) } } >> when Proc >> scl.class_eval { define_method(m,&mapped) } >> else >> raise ArgumentError, "Must be Proc or Symbol" >> end >> end >> end >> end >> >> With this we can do >> >> >> sample = %w{aa bb cc} >> >> => ["aa", "bb", "cc"] >> >> >> fake_class = Adaptor.new(sample, :new => :dup, :=== => :==) >> >> => ["aa", "bb", "cc"] >> >> >> x = fake_class.new >> >> => ["aa", "bb", "cc"] >> >> >> "Is an instance of? #{fake_class === x}" >> >> => "Is an instance of? true" >> >> >> x.id == sample.id >> >> => false > > Let me see if I understand this correctly. This is essentially a quick way > to > create an adapter class based on a preexisting object. Is that right, or > is > there more to it? That's it exactly. Kind of an extension of Delegator. > Also, what are you using this for? It seems cool enough, but I'm trying to > get > a fix on it's uses. Well, I presented one use, a fake class that implements important methods of a class. OTOH, it might be more appropriate to create a new class from scratch... In fact, this might be as easy: >> fake_class = Class.new do ?> @sample = %w{a b c d} >> def self.new() @sample.dup end >> def self.===(x) @sample == x end >> end => #<Class:0x101642b8> >> fake_class.new => ["a", "b", "c", "d"] >> fake_class.new.id => 134638608 >> fake_class.new.id => 134620092 >> fake_class === fake_class.new => true Hm... robert