考虑这个非常简单的日志记录类:
class MockLog
# ...
end
让我们为所有课程添加日志记录:
class Module
def has_logging()
class_eval {
@log = MockLog.new
def log
self.class.instance_variable_get :@log
end
}
end
end
现在,为什么这不起作用?
class Foo
has_logging
end
Foo.new.log.nil? # => false, as expected
class Bar < Foo
end
Bar.new.log.nil? # => true?! Why wasn't the `log` method inherited?
答案 0 :(得分:1)
log方法是继承的(如果不是,你会得到NoMethodError),但你的类级实例变量不是,所以instance_variable_get
返回nil。你应该声明一个常规的类变量,如:
class Module
def has_logging()
class_eval {
@@log = MockLog.new
def log
@@log
end
}
end
end
class Foo
has_logging
end
class Bar < Foo
end
现在它将被继承。见Class and Instance Variables In Ruby