如何让另一个模块包含的模块在包含模块中查找常量?换句话说,如何让下面的B.foo
和D.foo
给出预期的结果?
module A
module_function
public
def foo; C end
end
module B
extend A
C = "foo in B"
end
module D
extend A
C = "foo in D"
end
B.foo #=> (Expected) "foo in B"
D.foo #=> (Expected) "foo in D"
答案 0 :(得分:3)
您需要告诉它在C
A
所在的上下文中查找extend
:
module A
def foo
self::C
end
end
module B
extend A
C = "foo in B"
end
module D
extend A
C = "foo in D"
end
B.foo #=> "foo in B"
D.foo #=> "foo in D"
答案 1 :(得分:2)
我建议创建一个可供其他模块使用的属性初始值设定项:
module A
# This is actually executed in the context of each individual object.
# Since all modules and classes are also objects, each module extended
# by A gets to set its own state which the other methods can then use.
def attribute(*args)
@value = args.first if args.any?
@value || :default
end
def foo
attribute.to_s
end
end
module B
extend A
attribute :from_B
end
module C
extend A
attribute :from_C
end
module D
extend A
end
B.foo # => "from_B"
C.foo # => "from_C"
D.foo # => "default"
答案 2 :(得分:0)
你不能用常量来做这件事,因为它们不是继承的,但你可以使用方法:
module A
def foo
c
end
end
module B
extend A
def self.c
"foo in B"
end
end
module D
extend A
def self.c
"foo in D"
end
end
B.foo #=> "foo in B"
D.foo #=> "foo in D"