Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method on a Ruby module

Tags:

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?

like image 457
gsmendoza Avatar asked Dec 29 '09 08:12

gsmendoza


People also ask

How do you call a method inside a module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

How do I use modules in Ruby?

Creating Modules in Ruby To define a module, use the module keyword, give it a name and then finish with an end . The module name follows the same rules as class names. The name is a constant and should start with a capital letter. If the module is two words it should be camel case (e.g MyModule).


1 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" 
like image 163
Wayne Conrad Avatar answered Sep 22 '22 03:09

Wayne Conrad