lokanadham100
lokanadham100

Reputation: 1283

Why module_function creates a private method, when including the module?

The following code

module MyModule
 def module_func_a
  puts "module_func_a invoked"     
 end

 module_function :module_func_a
end

class MyClass
 include MyModule
end

MyClass.new.module_func_a

when executed hitting the error as follows

NoMethodError: private method `module_func_a' called for #<MyClass:0x007fb1f9026ae0>

After checking the doc for module_function here https://apidock.com/ruby/Module/module_function, found that module_function will make the mixin methods as private.

But What’s the intention for doing that?

Upvotes: 2

Views: 731

Answers (1)

Holger Just
Holger Just

Reputation: 55758

This is often used for modules containing helper or utility methods. Here, you can call the method directly on the module as MyModule.module_func_a. These methods are usually used similar to functions in other languages, i.e., they only refer to their arguments and have no intrinsic state.

Sometimes, it is desirable to use a lot of functionality of such a module in a class which makes it desirable to omit the explicit MyModule receiver from each such method. Thus, you can include the utility module in the class to make the methods available there.

Now, since those methods are intended to be used in the internal implementation of the methods of the class, the module's methods should not become part of the public interface of the class since they do not add any class-specific functionality.

And that's why the methods become private when included.

Upvotes: 4

Related Questions