Calling a method on a Ruby module

Viewed 29926

I have the following Ruby code:

module MyModule
  class MyClass
    def self.my_method
    end
  end
end

To call my_method, I enter MyModule::MyClass.my_method. I'd like to write a wrapper for my_method on the module itself:

MyModule.my_method

Is this possible?

3 Answers

I'm not sure what you're trying to achieve, but: if you make it a regular method and modify it with module_function, you will be able to call it any way you choose.

#!/usr/bin/ruby1.8

module MyModule

  def my_method
    p "my method"
  end
  module_function :my_method

end

Having done this, you may either include the module and call the method as an instance method:

class MyClass

  include MyModule

  def foo
    my_method
  end

end

MyClass.new.foo      # => "my method"

or you may call the method as a class method on the module:

MyModule.my_method   # => "my method"

Simple method:

module MyModule
  def self.my_method(*args)
    MyModule::MyClass.my_method(*args)
  end
end

Harder method:

Use metaprogramming to write a function for all cases (like attr_accessor).

You can define the method directly inside the module.

module MyModule
  def self.my_method
    puts "Hi I am #{self}"
  end
end

MyModule.my_method  #=> Hi I am MyModule
Related