简体   繁体   English

如何使用define_method定义?(超级)

[英]How to use defined?(super) with define_method

When I use define_method from within a block passed to an iterator, for some reason defined?(super) never evaluates to true . 当我在传递给迭代器的块中使用define_method ,由于某种原因defined?(super)从不求值为true

See the example below. 请参阅下面的示例。 Note that super(value) is a valid call, even though defined? 请注意,即使已defined?super(value) 也是有效的调用defined? thinks otherwise. 不这么认为。

class A
  def message=(val)
    puts 'A says ' + val
  end
end

class B < A
  ['message', 'warning'].each do |method|
    define_method(method + '=') do |val|
      puts 'B says ' + val
      super(val) if defined?(super)
    end
  end
end

a = A.new
a.message = 'hello!' # A says hello!
b = B.new
b.message = 'hello!' # B says hello!

############################################

class B < A
  ['message', 'warning'].each do |method|
    define_method(method + '=') do |val|
      puts 'B says ' + val
      super(val) rescue nil
    end
  end
end

b = B.new
b.message = 'hello!' # B says hello! A says hello!

This is a bug in Ruby 1.9.3 that was fixed in 2.0.0-p0 but never backported to 1.9.3. 这是Ruby 1.9.3中的一个错误 ,它在2.0.0-p0中修复但从未向后移植到1.9.3。 The reported bug isn't exactly the same, but its fix is likely what solved this. 报告的错误并不完全相同 ,但它的修复很可能解决了这个问题。

Likely this arose from the fact that defined? 可能这是由于defined?的事实引起的defined? and super are both keywords and the possible issues with scoping in a dynamic method definition via a Proc. super是关键字和通过Proc在动态方法定义中作用域的可能问题。 But I'm just guessing. 但我只是在猜测。

You should upgrade to Ruby 2.0 (or better yet 2.1) in order to fix this—or attempt to backport the patch yourself. 您应该升级到Ruby 2.0(或更好的2.1)以便修复此问题或尝试自行向后移植补丁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM