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?
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.
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).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With