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
Post a Comment