从该模块中的类访问模块方法?

时间:2022-11-25 08:37:39

Under Ruby 2.0, what is the correct way to access a module method from a class in that module?

在Ruby 2.0下,从该模块中的类访问模块方法的正确方法是什么?

For instance, if I have

例如,如果我有

module Foo
    class Foo
        def do_something
            Foo::module_method
        end
    end

    def self.module_method
        puts 'How do I call this?'
    end
end 

I get,

./so-module.rb:7:in do_something': undefined methodmodule_method' for Foo::Foo:Class (NoMethodError) from ./so-module.rb:16:in `'

./so-module.rb:7:in do_something':undefined methodmodule_method'for Foo :: Foo:Class(NoMethodError)from ./so-module.rb:16:in`

What is the correct way to define the module method so I can access it from class Foo?

定义模块方法的正确方法是什么,以便我可以从类Foo访问它?

2 个解决方案

#1


1  

You have to define the method on the module’s singleton class:

您必须在模块的singleton类上定义方法:

module Foo
  class Bar
    def do_something
      Foo.module_method
    end
  end

  def self.module_method
    'Success!'
  end
end

Foo::Bar.new.do_something  #=> "Success!"

#2


0  

Please take a look at following code:

请看下面的代码:

module Foo
    class Bar
        include Foo
        def do_something
            module_method
        end
    end
    def module_method
        puts 'How do I call this?'
    end
end

b = Foo::Bar.new
b.do_something

result:

How do I call this?

You can even try adding following code:

您甚至可以尝试添加以下代码:

b1 = Foo::Bar::Bar.new
b1.do_something

It's tricky and has same result:

这很棘手并且结果相同:

How do I call this?

#1


1  

You have to define the method on the module’s singleton class:

您必须在模块的singleton类上定义方法:

module Foo
  class Bar
    def do_something
      Foo.module_method
    end
  end

  def self.module_method
    'Success!'
  end
end

Foo::Bar.new.do_something  #=> "Success!"

#2


0  

Please take a look at following code:

请看下面的代码:

module Foo
    class Bar
        include Foo
        def do_something
            module_method
        end
    end
    def module_method
        puts 'How do I call this?'
    end
end

b = Foo::Bar.new
b.do_something

result:

How do I call this?

You can even try adding following code:

您甚至可以尝试添加以下代码:

b1 = Foo::Bar::Bar.new
b1.do_something

It's tricky and has same result:

这很棘手并且结果相同:

How do I call this?