module_function

What it does?

  • module_function allows 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

  1. Use module_function to use all the methods inside a module as class methods or
  2. Use module_function :name to 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