Jac*_*els 0 ruby class instance-methods
我有一个具有实例方法的类,它返回一个哈希.我无法直接更改该类的代码,但我可以使用模块扩展它.我需要在方法的返回哈希中添加一些新键.像这样的东西:
class Processor
def process
{ a: 1 }
end
end
module ProcessorCustom
def process
super.merge(b: 2) # Not works :(
end
end
Processor.send :include, ProcessorCustom
processor = Processor.new
processor.process # returns { a: 1 }, not { a: 1, b: 2 }
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?谢谢.
你可以打电话prepend而不是include:
Processor.prepend(ProcessorCustom)
processor = Processor.new
processor.process
#=> {:a=>1, :b=>2}
Run Code Online (Sandbox Code Playgroud)
prepend并include导致不同的祖先顺序:
module A; end
module B; end
module C; end
B.ancestors #=> [B]
B.include(C)
B.ancestors #=> [B, C]
B.prepend(A)
B.ancestors #=> [A, B, C]
Run Code Online (Sandbox Code Playgroud)
根据您的用例,您还可以extend使用特定实例:(这不会影响其他实例)
processor = Processor.new
processor.extend(ProcessorCustom)
processor.process
#=> {:a=>1, :b=>2}
Run Code Online (Sandbox Code Playgroud)
或者用于SimpleDelegator实现装饰器模式:
require 'delegate'
class ProcessorCustom < SimpleDelegator
def process
super.merge(b: 2)
end
end
processor = ProcessorCustom.new(Processor.new)
processor.process #=> {:a=>1, :b=>2}
Run Code Online (Sandbox Code Playgroud)