[英]Ruby: How to access a constant from the class a module is included into
我正在嘗試訪問我在其中包含的模塊中的各個類中保持的常量。 作為一個基本的例子
module foo
def do_something_to_const
CONSTANT.each { ... do_something ... }
end
end
class bar
include foo
CONSTANT = %w(I want to be able to access this in foo)
end
class baz
include foo
CONSTANT = %w(A different constant to access)
end
由於模塊的邏輯在多個類之間共享,我希望能夠僅引用常量(其名稱在每個類中保持相同,但內容不同)。 我該怎么做呢?
您可以將包含的類模塊引用為self.class
並使用const_get
或self.class::CONST
,后者稍快一些:
module M
def foo
self.class::CONST
end
end
class A
CONST = "AAAA"
include M
end
class B
CONST = "BBBB"
include M
end
puts A.new.foo # => AAAA
puts B.new.foo # => BBBB
您可以使用self.class
引用該類
module Foo
def do_something
self.class::Constant.each {|x| puts x}
end
end
class Bar
include Foo
Constant = %w(Now is the time for all good men)
end
class Baz
include Foo
Constant = %w(to come to the aid of their country)
end
bar = Bar.new
bar.do_something
=>
Now
is
the
time
for
all
good
men
=> ["Now", "is", "the", "time", "for", "all", "good", "men"]
baz = Baz.new
baz.do_something
=>
to
come
to
the
aid
of
their
country
=> ["to", "come", "to", "the", "aid", "of", "their", "country"]
您可以使用::
運算符將CONSTANT
范圍CONSTANT
為BAR
類。 語法看起來像這樣:
module Foo
def do_something_to_const
Bar::CONSTANT.each { |item| puts item }
end
end
class Bar
include Foo
CONSTANT = %w(I want to be able to access this in foo)
end
Bar.new.do_something_to_const # outputs each item in Bar::CONSTANT
不過,我會盡量避免這種情況。 包含的模塊不需要知道包含它的類的實現細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.