[英]Ruby - How to create a class variables to access in function
我想創建一個 function 來設置像attr_reader
這樣的實例變量
class Base
def exec
# get all functions to check
# if all functions return true
# I will do something here
end
end
然后我有一個 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
因為我只需要 1 個邏輯來在所有類中執行,但我對每個 class 有很多不同的檢查,我需要靈活地進行。
請給我一個關鍵字。
非常感謝。
為了有check:check_1
您需要將check
定義為class 方法:
class Base
def self.check(name)
# ...
end
end
由於您想稍后調用傳遞的方法名稱,我會將它們存儲在一個數組中:(由另一個 class 方法checks
提供)
class Base
def self.checks
@checks ||= []
end
def self.check(name)
checks << name
end
end
這已經為您提供:
SomeClass.checks
#=> [:check_1, :check_2]
Some2Class.checks
#=> [:check_3, :check_4]
現在您可以從exec
中遍歷這個數組並通過send
調用每個方法。 可以全部使用all?
檢查它們是否都返回了真實的結果:
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
需要self.class
部分,因為您從實例方法exec
調用class方法checks
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.