Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Patch method will always defer to any pre-defined method of same name,
- # only use Patch implementation if method not already defined.
- # An error could still occur if the pre-defined method expects a different
- # number of parameters.
- # By defining in a module rather than direct patching of the class, the
- # patch method won't even be used if method already defined directly as an
- # instance method on the class (i.e. not from some other mix-in module).
- module Patch
- def a_method(x, y, z)
- return super(x, y, z) if defined? super
- x * y * z
- end
- end
- module Mixin
- def a_method(x, y, z)
- return x + y + z
- end
- end
- class A
- def a_method(x, y, z)
- return x + y + z
- end
- end
- class B
- include Mixin
- end
- class C
- end
- A.send :include, Patch
- B.send :include, Patch
- C.send :include, Patch
- puts A.new.a_method(2, 3, 4) # 2 + 3 + 4 = 9 -- use method defined in class
- puts B.new.a_method(2, 3, 4) # 2 + 3 + 4 = 9 -- delegate to method from Mixin
- puts C.new.a_method(2, 3, 4) # 2 * 3 * 4 = 24 -- use method from Patch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement