Ruby 学习:Forwardable

可转发模块使用def_delegator和def_delegator方法将指定方法委托给指定对象。
更新于: 2021-12-30 06:37:24

转发一个成员 def_delegator

例如,假设您有一个类RecordCollection,其中包含一个数组@records。您可以提供查找方法record_number(),该方法只需在@records数组上调用[],如下所示:

require 'forwardable'

class RecordCollection
  attr_accessor :records
  extend Forwardable
  def_delegator :@records, :[], :record_number
end

转发多个成员 def_delegators

class RecordCollection # re-open RecordCollection class
  def_delegators :@records, :size, :<<, :map
end

r = RecordCollection.new
r.records = [1,2,3]
r.record_number(0)   # => 1
r.size               # => 3
r << 4               # => [1, 2, 3, 4]
r.map { |x| x * 2 }  # => [2, 4, 6, 8]

参考