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?
Also, what are you using this for? It seems cool enough, but I'm trying to get
a fix on it's uses.
T.
···
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_symunless 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
endWith 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