红宝石模块与包入类的静态方法调用
问题描述:
我需要定义使用的方法从类的模块包括该模块中的常量:红宝石模块与包入类的静态方法调用
module B
def self.included(base)
class << base
CONST = self.find
end
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
但是编译器为4号的错误线。
有没有其他方法来定义常量?
答
更习惯的方法在Ruby中实现这一目标是:
module B
def self.included(klass)
klass.class_eval <<-ruby_eval
CONST = find
ruby_eval
# note that the block form of class_eval won't work
# because you can't assign a constant inside a method
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
你在做什么(类< <基地)其实是把你变成的metaclass
的背景下,没有A本身。 find
方法在A本身上,而不是它的元类。需要记住的是,类本身就是对象,所以它们有自己的元类。
要尽量说得清楚:
class Human
def parent
# this method is on the Human class and available
# to all instances of Human.
end
class << self
def build
# this method is on the Human metaclass, and
# available to its instance, Human itself.
end
# the "self" here is Human's metaclass, so build
# cannot be called.
end
def self.build
# exactly the same as the above
end
build # the "self" here is Human itself, so build can
# be called
end
不知道是否有帮助,但如果你不明白,你仍然可以使用上面的class_eval成语。
答
在你的具体情况。
module B
def self.included(base)
base.const_set("CONST", base.find)
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
尽管它有效,但有点混乱。你确定你不能按照不同的方式来实现你的目标吗?
答
module B
def self.included(base)
class << base
CONST = self.find
end
end
end
class A
class << self
def self.find
"AAA"
end
end
include B
end
然后编译器错误是固定的,请尝试。
是的,我也达到这个解决方案。但那个元调用不是很好的主意。有更直的方法吗? – 2009-06-26 18:05:21