evanmcdonnal
evanmcdonnal

Reputation: 48086

Can you redefine a mixin's method in the class which implements it

I'm new to Ruby and was reading this post comparing a mixin to a C# interface. What is unclear to me is whether or not a method from the mixin can be redefined in the class which implements it.

For example, if I put include myMixin — which has a method toJSON — in a class MyClass, can I redefine toJSON in MyClass, or am I stuck with the behavior defined in myMixin?

For anyone with further interest, is that blog post a good source of information? Is it reasonable to compare a Ruby mixin to a C# interface?

Upvotes: 0

Views: 427

Answers (3)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

include makes the module the superclass of the class you are mixing it into. Obviously, you can override methods of a superclass in a subclass, that's just how subclassing works, not just in Ruby but in pretty much any other class-based OO language as well.

Upvotes: -1

wless1
wless1

Reputation: 3549

methods defined in a class will always override methods mixed into that class through a module in Ruby

For example:

module Bang
   def bar
      "lol"
   end
end

class Foo
   include Bang
   def bar
      42
   end
end

Foo.new.bar
 => 42 

Regardless of when the module is included, the method bar defined on the class will be called first. This is because of how ruby looks up methods - it searches the class itself before it searches any modules included into the class.

http://anders.janmyr.com/2009/06/ruby-method-lookup.html

http://blog.rubybestpractices.com/posts/gregory/031-issue-2-method-lookup.html

Upvotes: 2

Daniel Evans
Daniel Evans

Reputation: 6808

No you are not stuck, you can override the method with either more mixin modules, or by redefining the method after you include the mixin.

You can decide in your new method to let the mixin handle it by calling super, just like inheritance.

Something you should realize about Ruby since you are coming from a C# background is that ruby's methods are never "stuck." At any time you can redefine methods, even on core language classes like Object or Class. This is dangerous, but possible. You can programmatically alter the language, create new classes or do other metaprogramming voodoo.

Upvotes: 1

Related Questions