Operator overload through mixin

Is there a way to override the class operator by creating a new new operator method inside the module and then moving that module to the class?

for example, this overrides the Fixnum + operator:

class Fixnum def +(x) product = x product = product * self return product end end p 3 + 3 # => 9 

This does not override the Fixnum + operator:

 module NewOperators def +(x) product = x product = product * self return product end end class Fixnum include NewOperators end p 3 + 3 # => 6 
+6
source share
2 answers

Your question led me to this interesting article that describes the problem:

Fixing an inheritance model in Rubys with a metamorph

This is the final problem with the Rubys inheritance model, in my opinion. Since mixins always take a lower priority than methods defined directly in the class, A # foo cannot be overridden by the inclusion of mixin. Moreover, since mixins take a lower priority than methods, A # foo now breaks encapsulation [...]

And his solution is to transparently define all new methods inside an anonymous internal module:

 class Object def self.method_added(name) return if name == :initialize const_set(:InstanceMethods, Module.new) unless defined?(self::InstanceMethods) meth = instance_method(name) self::InstanceMethods.send(:define_method, name) {|*args, &block| meth.bind(self).call(*args, &block) } remove_method(name) include self::InstanceMethods end end 

It is also conveniently packaged in a library called metamorph , which allows you to use mixin methods to override class methods, just requiring it.

+3
source

No, because in the search for a method you do not get the opportunity to use methods that were defined in mixins or parent classes until you really looked at the current class.

However, you can create a method that when you call the class will create methods in this class. This can give you the ability to easily enter operators into classes.

Be warned that this is actually a good recipe for surprise. This is doubly true when you change standard modules whose behavior depends on others. See http://avdi.org/devblog/2008/02/23/why-monkeypatching-is-destroying-ruby/ for context.

+3
source

Source: https://habr.com/ru/post/890200/


All Articles