[英]Ruby - How to create a class variables to access in function
I want to create a function to set the instance variable like attr_reader
我想创建一个 function 来设置像attr_reader
这样的实例变量
class Base
def exec
# get all functions to check
# if all functions return true
# I will do something here
end
end
And then I have a class inherit Base
.然后我有一个 class 继承Base
。
class SomeClass < Base
check :check_1
check :check_2
def check_1
# checking
end
def check_2
# checking
end
end
class Some2Class < Base
check :check_3
check :check_4
def check_3
# checking
end
def check_4
# checking
end
end
Because I only need 1 logic for executing in all classes but I have a lot the different checks for each class, I need to do it flexibly.因为我只需要 1 个逻辑来在所有类中执行,但我对每个 class 有很多不同的检查,我需要灵活地进行。
Please, give me a keyword for it.请给我一个关键字。
Many thanks.非常感谢。
In order to have check:check_1
you need to define check
as a class method :为了有check:check_1
您需要将check
定义为class 方法:
class Base
def self.check(name)
# ...
end
end
Since you want to call the passed method names later on, I'd store them in an array: (provided by another class method checks
)由于您想稍后调用传递的方法名称,我会将它们存储在一个数组中:(由另一个 class 方法checks
提供)
class Base
def self.checks
@checks ||= []
end
def self.check(name)
checks << name
end
end
This already gives you:这已经为您提供:
SomeClass.checks
#=> [:check_1, :check_2]
Some2Class.checks
#=> [:check_3, :check_4]
Now you can traverse this array from within exec
and invoke each method via send
.现在您可以从exec
中遍历这个数组并通过send
调用每个方法。 You can use all?
可以全部使用all?
to check whether all of them return a truthy result:检查它们是否都返回了真实的结果:
class Base
# ...
def exec
if self.class.checks.all? { |name| send(name) }
# do something
end
end
end
SomeClass.new.exec # doesn't do anything yet
The self.class
part is needed because you are calling the class method checks
from the instance method exec
.需要self.class
部分,因为您从实例方法exec
调用class方法checks
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.