DEV Community

Discussion on: Prefer Ruby Class Method or Mix-In Instance Method?

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

A require 'foo' does not alter your class. It just gives you access to call Foo.foo(). There's nothing happening in terms of inheritance or composition. It's maybe the simplest form of dependency between your class and Foo. If you only want to call one method or another in Foo, then yes, that's the way to go.

But when calling include Bar there's a lot happening. You not only get access to bar(), but also to all other methods that are in Bar. And they are directly available in the namespace of your instance. And maybe even class methods have been defined, so the include might have also given you YourClass.baz(). You better know exactly what's in Bar, because your class might get cluttered with a lot of stuff... it's actually pretty similar to inheritance. So the actual question when it comes to include is: ruby inheritance vs. mixins. And I like this answer very much:

Modules are for sharing behavior, while classes are for modeling relationships between objects.

So back to your question - you should use include when you want your class to get (all) the behaviour the module gives you. And you should not use it if you just want to call a method.