tags:

views:

64

answers:

3

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?

+1  A: 

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
anshul
+2  A: 

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).

ChaosR
Thanks. Funny how this didn't work for me yesterday. But it works now! :)
gsmendoza
I think I know now why it didn't work before: I had the MyModule.my_method declaration in one file (my_module.rb) and the MyModule::MyClass.my_method in another file (my_class.rb). When I put the above method inside my_class.rb, MyModule.my_method worked!
gsmendoza
A: 

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

class MyClass

  include MyModule

  def foo
    my_method
  end

end

MyClass.new.foo      # => "my method"
MyModule.my_method   # => "my method"
Wayne Conrad