From: Robert Klemme Date: 2004-11-19T23:13:17+09:00 Subject: Re: Delegating a method, with arguments "Daniel Berger" schrieb im Newsbeitrag news:6e613a32.0411182145.45683083@posting.google.com... > Hi all, > > I'm trying to write a class where I want to delegate some instance > methods as FileTest class methods. For example: > > require "forwardable" > class Foo < String > extend Forwardable > def_delegator(:FileTest,:directory?) > def initialize(path) > @path = path > end > end > > This doesn't work, however, since FileTest.directory? requires an > argument. What I would like is something like the following fictional > syntax: > > def_delegator(:FileTest,:directory?(@path)) > > I don't want to create an instance of File and delegate to that > instance because I don't know if @path will actually be valid or not > (among other reasons). > > So, would something like this be possible? This is easy but doesn't keep arity: class Module def def_delegator(instance_var, *syms) syms.each do |m| class_eval "def #{m}(*a,&b) #{instance_var}.#{m}(*a,&b) end" end end end class Foo attr_accessor :bar def_delegator("@bar", :foo) end class Bar def foo() "yes" end end >> f=Foo.new => # >> f.bar = Bar.new => # >> f.foo => "yes" With more effort and the additional info of the target class you can determine the target method's arity and use that. However, the only benefit is that clients who ask your delegator method for it's arity see the real method's arity. Kind regards robert