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}”
end
#module_function(:foo) # use if no private methods are used by module methods. (http://ruby-doc.org/core/classes/Module.src/M001642.html)
def bar
“This is bar”
end
private
def baz
“hi there”
end
end
puts A.foo #output is: foo: undefined local variable or method ‘baz’ for A:Module
[/source]
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 A.foo #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 *