module_function
What it does?
-
module_functionallows exposing instance’s methods so they can be called as they would be class methods.
module User
def name
'Hello Sam'
end
end
If you try to do this:
user = User.new
user.name
You're gonna receive an error because modules do not respond to the new method.
How can we use it?
You can use this useful method module_function:
module User
module_function
def name
'Hello Sam'
end
end
And call the name method like User.name
- Use
module_functionto use all the methods inside a module as class methods or - Use
module_function :nameto only apply it in a specific method
A second option to do it
Another option to do so is using extend self instead:
module User
extend self
def name
'Hello Sam'
end
end
