[英]Code duplication in a module methods of class and instance levels
我有Memoize模块,该模块提供用于缓存类和实例方法的方法。
module Memoize
def instance_memoize(*methods)
memoizer = Module.new do
methods.each do |method|
define_method method do
@_memoized_results ||= {}
if @_memoized_results.include? method
@_memoized_results[method]
else
@_memoized_results[method] = super()
end
end
end
end
prepend memoizer
end
def class_memoize(*methods)
methods.each do |method|
define_singleton_method method do
@_memoized_results ||= {}
if @_memoized_results.include? method
@_memoized_results[method]
else
@_memoized_results[method] = super()
end
end
end
end
end
这是我如何使用它的一个示例:
class Foo
extend Memoize
instance_memoize :instance_method1, :instance_method2
class_memoize :class_method1, :class_method2
...
end
请在此模块中建议如何避免代码重复。
可能会定义一个lambda :
λ = lambda do
@_memoized_results ||= {}
if @_memoized_results.include? method
@_memoized_results[method]
else
@_memoized_results[method] = super()
end
end
和。 然后:
define_method method, &λ
请注意λ
前面的与号,它用于注意define_method
正在接收一个块,而不是常规参数。
我没有遇到这种方法失败的地方,但是这里是防弹的版本:
method_declaration = %Q{
def %{method}
@_memoized_results ||= {}
if @_memoized_results.include? :%{method}
@_memoized_results[:%{method}]
else
@_memoized_results[:%{method}] = super()
end
end
}
methods.each do |method|
class_eval method_declaration % {method: method}
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.