Ruby: Calling Methods in a Module Directly.


38 sec read

Private methods cannot be called directly. If you intend to call a method in a module with the same namespace then module_function () is helpful. But if the module method accesses a private method then it cannot be accessed.
Here is a way to do that.

[source language=”ruby”]
module A
extend A # used if module methods access the private methods.
def foo # instance method of this module. ? or module method
“This is foo calling baz: #{baz}”
#module_function(:foo) # use if no private methods are used by module methods. (
def bar
“This is bar”
def baz
“hi there”
puts #output is: foo: undefined local variable or method ‘baz’ for A:Module
Thats because module_function does not allow you to access the private methods. A way to do this is by extending the module in the module.
Add extend A to the module.
Now #output: This is foo calling bar. hi there.
Hope someone will find this useful.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *