调用Ruby模块上的方法

时间:2020-12-19 23:19:30

I have the following Ruby code:

我有以下Ruby代码:

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:

要调用my_method,我输入MyClass.my_method模块::MyClass.my_method。我想在模块本身上为my_method编写一个包装:

MyModule.my_method

Is this possible?

这是可能的吗?

3 个解决方案

#1


13  

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

使用元编程为所有情况(如attr_accessor)编写函数。

#2


27  

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.

我不确定您想要实现什么,但是:如果您使它成为一个常规方法并使用module_function对其进行修改,那么您将能够任意调用它。

#!/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"

#3


9  

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

#1


13  

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

使用元编程为所有情况(如attr_accessor)编写函数。

#2


27  

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.

我不确定您想要实现什么,但是:如果您使它成为一个常规方法并使用module_function对其进行修改,那么您将能够任意调用它。

#!/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"

#3


9  

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