[英]Code duplication in a module methods of class and instance levels
I have Memoize module, that provides methods for caching of class and instance methods. 我有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
This is an example of how I use it: 这是我如何使用它的一个示例:
class Foo
extend Memoize
instance_memoize :instance_method1, :instance_method2
class_memoize :class_method1, :class_method2
...
end
Please advice how to avoid code duplication in this module. 请在此模块中建议如何避免代码重复。
One might define a lambda : 可能会定义一个lambda :
λ = lambda do
@_memoized_results ||= {}
if @_memoized_results.include? method
@_memoized_results[method]
else
@_memoized_results[method] = super()
end
end
And. 和。 then:
然后:
define_method method, &λ
Please be aware of an ampersand in front of λ
, it is used to notice define_method
about it's receiving a block, rather than a regular argument. 请注意
λ
前面的与号,它用于注意define_method
正在接收一个块,而不是常规参数。
I did not get what failed with this approach on your side, but here is a bullet-proof version: 我没有遇到这种方法失败的地方,但是这里是防弹的版本:
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.