ruby - Extend return value of class instance method -


i have class have instance method, returns hash. can't change code of class directly, can extend modules. need add new keys returning hash of method. this:

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 } 

how can that? thanks.

you call prepend instead of include:

processor.prepend(processorcustom)  processor = processor.new processor.process #=> {:a=>1, :b=>2} 

prepend , include result in different ancestor order:

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] 

alternatives

depending on use-case, extend specific instance: (this doesn't affect other instances)

processor = processor.new processor.extend(processorcustom) processor.process #=> {:a=>1, :b=>2} 

or use simpledelegator implement decorator pattern:

require 'delegate' class processorcustom < simpledelegator   def process     super.merge(b: 2)   end end  processor = processorcustom.new(processor.new) processor.process  #=> {:a=>1, :b=>2} 

Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -