【发布时间】:2012-11-04 16:18:21
【问题描述】:
我有一个模块可以调用“计算器”,我想将它包含在“产品”类中。 Calculator 将扩展“Product”,它将类方法复制到 Product。这些类方法之一是“memoize”。我的想法是我可以做这样的事情:
module Calculator
def self.extended(base)
base.memoize :foo_bar
end
end
为了记忆方法(特别是类方法):foo_bar。在 memoize 内部,我将方法称为“alias_method”,它尝试将类方法别名为不同的名称(此处为:foo_bar)。这失败了。 Memoize 看起来像:
module Calculator (the extended module)
def memoize(name)
alias_method "memoized_#{name}", name
end
end
当通过 memoize :foo_bar 调用它时,alias_method 行会出现错误,说 Product has no method "name".. 我的理解是这是因为 alias_method 将尝试为实例方法而不是类方法..(我不不知道为什么,但没什么大不了的)..
我可以像这样重新打开特征类
module Calculator
def memoize(name)
class << self
alias_method "memoized_#{name}", name
end
end
end
这可行,但名称在类
【问题讨论】:
标签: ruby