Ruby 转发到访问器方法返回的对象

Ruby forwarding to a object returned by accessor method

我有一个class,大致结构如下:

class X
  def initialize
    @container = Container.new
    ....
  end
  def store
    @container.get_store
  end
  def f
    store.f
  end
  def g
    store.g
  end
  def h
    store.h
  end
  ....
end

可以看出,我有几个方法,只是简单地“转发”到 store,只是 store 不是实例变量,但是无参数方法的结果。有没有一种紧凑的方法来实现这种转发?如果 store 总是 return 相同的对象,我可以这样做:

class X
  extend Forwardable
  def initialize
    container = Container.new
    @store = container.the_store
  end
  def_delegator :@store, .f, :g, :h
end

但我不能依赖这个; @container.the_store 可能会在实例的生命周期内发生变化。我考虑的另一种选择是

class X
  [:f,:g,:h].each do |meth_sym|
    define_method(meth_sym) do |*args|
      store.public_send(meth_sym, *args)
    end
  end
  def store
    @container.get_store
  end
end

但这看起来很笨拙。任何人都可以为我的问题提出不同的解决方案吗?

来自 Forwardable#def_instance_delegator 的文档:

accessor should be a method name, instance variable name, or constant name.

示例:(符号和字符串都有效,. 等同于 ::

def_delegator :@store, :f     # delegates f to instance variable @store
def_delegator :store, :f      # delegates f to instance method store
def_delegator 'X.store', :f   # delegates f to class method store
def_delegator 'X::Store', :f  # delegates f to constant X::Store

因为你有一个实例方法,你想要:store(没有@