我可以使用Forwardable在Ruby中委派常量吗? [英] Can I use Forwardable to delegate a constant in Ruby?

查看:64
本文介绍了我可以使用Forwardable在Ruby中委派常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个像这样的类:

class Thing
  CONSTANT = 10
  # other code
end

另一个类似:

class Other
  def initialize
    @thing = Thing.new
  end

  def method
    puts CONSTANT
  end
end

是否可以扩展 Forwardable Other CONSTANT 委托给 Thing 的常量?

Is it possible to extend Forwardable to have Other's CONSTANT delegate to Thing's constant?

我尝试扩展 SingleForwardable (请参阅文档此处),例如:

I have tried extendingSingleForwardable (see docs here ) like so:

class Other
  extend SingleForwardable

  def initialize
    @thing = Thing.new
  end

  def method
    puts CONSTANT
  end

  def_single_delegator :@thing, :CONSTANT
end

并且:

def_single_delegator :@thing, :constant

但都没有用,我语法是否错误?如果没有,还有其他方法吗?

but neither worked, am I getting the syntax wrong? If not, is there another way?

推荐答案

此方法由文档(粗体强调类)

This one is answered by the documentation (bold emphasis mine):


def_single_delegator(访问器,方法,new_name =方法)


定义委托给访问者方法 方法(即调用 accessor中具有相同名称的方法 )。如果提供了 new_name ,它将用作委托方法的名称。

def_single_delegator(accessor, method, new_name=method)

Defines a method method which delegates to accessor (i.e. it calls the method of the same name in accessor). If new_name is provided, it is used as the name for the delegate method.

因此,不,您只能委托消息发送,而不是持续查找。

So, no, you can only delegate message sends, not constant lookup.

这篇关于我可以使用Forwardable在Ruby中委派常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆