如何编写一个ruby模块,对包含它的类施加一些条件,这些条件必须满足当前打开的类定义的末尾?ruby模块如何对包含它的类执行条件?
要具体,假设条件是“一个类变量@@foo
应该被定义为> 0”
我想写一个模块,看起来是这样的:
module NeedPositiveFoo
module ClassMethods
def validate_positive_foo
raise unless defined?(@@foo) && @@foo > 0
end
end
def included(other)
other.extend(ClassMethods)
end
end
那么这个类的定义是有效的:他们的收盘end
的后
class ValidClass
include NeedPositiveFoo
@@foo = 3
end
但这些类定义将提高:
class InvalidClass1
include NeedPositiveFoo
# @@foo is not defined
end
class InvalidClass2
include NeedPositiveFoo
@@foo = -2
end
没有“类定义的末尾”这样的东西。随时可以在任何时候打开课程主体。或者如果你的意思是语法级别,那么你可以使用TracePoint。 – sawa
@sawa这是不正确的。有“当前打开的类定义的结束”这样的东西,适用于'included'回调中。 – mudasobwa
@mudasobwa你指的是语法级别。你说得对,但我的意思是另一回事。 – sawa