ruby模块如何在包含它的类上强制执行条件? [英] How can a ruby module enforce conditions on classes in which it is included?
问题描述
我如何编写一个ruby模块,对包含它的类强加一些条件,必须在当前打开的类定义的末尾满足该条件?
How can I write a ruby module that imposes some conditions on classes in which it is included, which must be met the end of currently opened class definition?
具体来说,假设条件是类变量@@foo
应该定义为> 0"
To be concrete, suppose the condition is "a class variable @@foo
should be defined to be >0 "
我想编写一个看起来像这样的模块:
I'd like to write a module that looks something like this:
module NeedPositiveFoo
module ClassMethods
def validate_positive_foo
raise unless defined?(@@foo) && @@foo > 0
end
end
def included(other)
other.extend(ClassMethods)
end
end
然后该类定义将有效:
class ValidClass
include NeedPositiveFoo
@@foo = 3
end
但是这些类定义将在它们的end
结束后引发:
But these class definitions would raise after their closing end
's:
class InvalidClass1
include NeedPositiveFoo
# @@foo is not defined
end
class InvalidClass2
include NeedPositiveFoo
@@foo = -2
end
推荐答案
当您允许在类定义的末尾添加include时,Uri Agassi的回答非常有效,尽管include
被放置.
While the answer by Uri Agassi perfectly works when you are allowed to put includes in the very end of class definition, the code below will work despite where include
was placed.
def included(other)
TracePoint.new(:end) do |tp|
if tp.self == other
tp.disable
raise unless defined?(other.class_variable_get(:@@foo)) # checks
end
end.enable
other.extend(ClassMethods)
end
这篇关于ruby模块如何在包含它的类上强制执行条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!