如何获取模块中定义的所有细化?
How to get all refinements defined in a module?
在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]
?
已更新
有点难看,但能用。您应该知道模块名称和 refine:
的 class
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]
在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]
?
已更新
有点难看,但能用。您应该知道模块名称和 refine:
的 classmodule 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]