Robert Klemme
11/19/2004 2:13:00 PM
"Daniel Berger" <djberg96@hotmail.com> 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
=> #<Foo:0x101a4030>
>> f.bar = Bar.new
=> #<Bar:0x1019ecc0>
>> 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