SingleForwardable
module SingleForwardable
SingleForwardable也可用于在对象级别设置委派。
printer = String.new
printer.extend SingleForwardable # prepare object for delegation
printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
printer.puts "Howdy!"
此外,SingleForwardable可用于设置类或模块的委派。
class Implementation
def self.service
puts "serviced!"
end
end
module Facade
extend SingleForwardable
def_delegator :Implementation, :service
end
Facade.service #=> serviced!
如果你想同时使用Forwardable和SingleForwardable,你可以使用def_instance_delegator和#def_single_delegator等方法。
公共实例方法
def_delegator(accessor, method, ali = method)
Alias for: def_single_delegator
def_delegators(accessor, *methods)
Alias for: def_single_delegators
def_single_delegator(accessor, method, new_name=method) Show source
定义一个方法
,方法
委托给该存取器
(即它调用同一个名字的方法
访问
)。如果提供了new_name
,它将用作委托方法
的名称。
# File lib/forwardable.rb, line 298
def def_single_delegator(accessor, method, ali = method)
gen = Forwardable._delegator_method(self, accessor, method, ali)
instance_eval(&gen)
end
Also aliased as: def_delegator
def_single_delegators(accessor, *methods) Show source
用于定义多个委托人方法的快捷方式,但没有规定使用不同的名称。以下两个代码示例具有相同的效果:
def_delegators :@records, :size, :<<, :map
def_delegator :@records, :size
def_delegator :@records, :<<
def_delegator :@records, :map
# File lib/forwardable.rb, line 284
def def_single_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_single_delegator(accessor, method)
end
end
Also aliased as: def_delegators
delegate(hash)
Alias for: single_delegate
delegate method → accessor Show source
delegate method, method, ... → accessor
以散列为参数。关键是一个符号或一系列符号。这些符号对应于方法名称。该值是该方法将被委派到的访问器。
# File lib/forwardable.rb, line 263
def single_delegate(hash)
hash.each do |methods, accessor|
unless defined?(methods.each)
def_single_delegator(accessor, methods)
else
methods.each {|method| def_single_delegator(accessor, method)}
end
end
end
Also aliased as: delegate