【发布时间】:2012-02-24 08:36:58
【问题描述】:
在 Ruby 中,<ClassName>.constants 对于检查类很有用:
> Numeric.constants(false)
=> [:KILOBYTE, :MEGABYTE, :GIGABYTE, :TERABYTE, :PETABYTE, :EXABYTE]
> Object.constants(false)
=> [:Object, :Module, ...]
这是在Module中定义的:
> Object.method(:constants)
=> #<Method: Class(Module)#constants>
我想添加另一种方法来打印包含所有常量及其值的哈希。到目前为止的结果如下:
def Module.constants_hash(inherit=true)
self.constants(inherit).inject({}) do |hash, constant|
hash[constant] = self::const_get(constant)
hash
end
end
这适用于Module(虽然它没有常量,所以结果只是一个空哈希),但它不是继承的:
> Object.constants_hash(false)
NoMethodError: undefined method `constants_hash' for Object:Class
from (pry):117:in `<main>'
我当然可以将代码中的类名更改为例如Object 使调用工作,但是是否有可能使所有依赖模块也继承新方法?换句话说,是否可以在运行时添加一个方法,然后由 require 修改后的类继承?
我宁愿不要重载原始的Module.constants,以避免更改 API。
【问题讨论】:
标签: ruby inheritance metaprogramming