【问题标题】:accessing instance methods from class method proc从类方法 proc 访问实例方法
【发布时间】:2013-11-23 20:06:55
【问题描述】:

我试图在一个类上调用一个 proc,但使用继承的类从它访问实例方法。我认为一些模拟代码会更有意义:)

class Bar
  def self.foo &block
    @foo ||= block
  end
  def foo; self.class.foo.call(); end
  def bar; 'bar'; end
end

class Foo < Bar
  foo do
    bar
  end
end

Foo.new.foo
# NameError: undefined local variable or method `bar' for Foo:Class

我希望能够访问 Bar 类上的 bar 实例方法。使用继承类中的块调用 foo 类方法的原因是 DSL 要求的一部分,但任何关于更好设计的建议都将不胜感激。

【问题讨论】:

  • 这两个 foo 令人困惑。
  • 为什么new.bar 或将bar 做成类方法不好?
  • @SergioTulentsev 哈哈!抱歉......我的设计代码不是很有创意:)

标签: ruby


【解决方案1】:

块是词法范围的,包括self 的值。在定义块的地方,selfBar 并且Bar 不响应bar。您需要在要调用其方法的对象(在本例中为Bar 而不是Bar 本身的instance)上下文中评估块。这就是instance_eval 所做的:

class Bar
  def self.foo(&block) @foo ||= block end
  def foo; instance_eval(&self.class.foo) end
  def bar; 'bar' end
end

class Foo < Bar; foo do bar end end

Foo.new.foo
# => 'bar'

请注意,所有关于 instance_eval 的常见免责声明都适用:因为您更改了块作者可能期望可用的 self 方法和实例变量的值。

【讨论】:

  • 完美!我之前实际上是在玩 instance_eval ,但它不起作用,因为我没有使用 & 符将其转换为 proc。但现在它是有道理的。谢谢你!
猜你喜欢
  • 2015-07-09
  • 2017-05-12
  • 2021-06-03
  • 2014-01-26
  • 1970-01-01
  • 2013-09-08
  • 2018-11-03
  • 2016-05-20
  • 1970-01-01
相关资源
最近更新 更多