Ruby 使def_委托人尊重私有方法
是否可以使Ruby 使def_委托人尊重私有方法,ruby,metaprogramming,access-specifier,Ruby,Metaprogramming,Access Specifier,是否可以使可转发#def_delegator方法考虑到目标方法是私有的 在下面的代码中,当使用def#u delegator时,调用Foo#hello,即使它是私有的,因为Forwardable#def#u delegator的实现(实际上,def#u instance_delegator)使用\uu发送,这不尊重私有的方法 require "forwardable" class Foo def hello "Hello" end private :hello end c
可转发#def_delegator
方法考虑到目标方法是私有的
在下面的代码中,当使用def#u delegator
时,调用Foo#hello
,即使它是私有的,因为Forwardable#def#u delegator
的实现(实际上,def#u instance_delegator
)使用\uu发送
,这不尊重私有的方法
require "forwardable"
class Foo
def hello
"Hello"
end
private :hello
end
class Bar
extend Forwardable
def_delegator :@foo, :hello
def initialize
@foo = Foo.new
end
def bar
hello
end
end
foo = Foo.new
foo.hello # => NoMethodError: private method `hello' called for #<Foo:0x007f57c3cd1c80>
bar = Bar.new
bar.bar # => "Hello"
要求“可转发”
福班
你好
“你好”
结束
二等兵:你好
结束
分类栏
扩展可转发
def_delegator:@foo,:你好
def初始化
@foo=foo.new
结束
def棒
你好
结束
结束
foo=foo.new
foo.hello#=>NoMethodError:调用了私有方法“hello”#
bar=bar.new
bar.bar#=>“你好”
我使用的是Ruby 2.0。不是直接使用的。如果您使用的是Active Support core extensions 4.0或更高版本,则可以使用
模块#委托
:
require "active_support/core_ext/module/delegation"
class Foo
def hello
"Hello"
end
private :hello
end
class Bar
delegate :hello, :to => :@foo
def initialize
@foo = Foo.new
end
def bar
hello
end
end
不直接。如果您使用的是Active Support core extensions 4.0或更高版本,则可以使用
模块#委托
:
require "active_support/core_ext/module/delegation"
class Foo
def hello
"Hello"
end
private :hello
end
class Bar
delegate :hello, :to => :@foo
def initialize
@foo = Foo.new
end
def bar
hello
end
end
你使用的是什么版本的Ruby?如果>=1.9,您可以重新定义
Forwardable#def_delegator
以使用您使用的Ruby版本?如果>=1.9,您可以重新定义可转发的#def_delegator
以使用