在ruby中,是否可以获取模块中定义的所有细化的列表?
例如,鉴于此:
module MyRefinements
refine String do
def foo
"#{self}_foo"
end
def trim
"this is not a good example, but demonstrates an override"
end
end
end
如何获得这样的数组:[:foo, :trim]
?
答案 0 :(得分:2)
<强>更新强>
有点难看,但工作。您应该知道模块名称和精炼类:
module MyRefinements
refine String do
def foo
"#{self}_foo"
end
def to_str
"this is not a good example, but demonstrates an override"
end
end
end
# Provide module name and class (type)
def get_refinements mod, type
ret = []
mod.module_eval do
refine type do
ret = self.ancestors
.select{|el| el.to_s.include? "refinement" }
.map{|el| el.instance_methods(false)}.flatten
end
end
ret
end
module Test
p get_refinements(MyRefinements, String)
end
输出是:
#=> [:to_str, :foo]