Rails:我不能在/ lib的模块中调用函数 – 我在做什么错了?

我知道我正在做一些愚蠢的事情,或者没有做一些聪明的事情 – 我经常犯两个罪。

以下是导致我痛苦的一个例子:

我有一个模块保存在/ lib作为test_functions.rb看起来像这样

module TestFunctions def abc puts 123 end end 

进入ruby脚本/转轮,我可以看到模块正在自动加载(良好的惯例超过configuration和所有…)

 >> TestFunctions.instance_methods => ["abc"] 

所以方法是已知的,让我们尝试调用它

 >> TestFunctions.abc NoMethodError: undefined method `abc' for TestFunctions:Module from (irb):3 

不。 这个怎么样?

 >> TestFunctions::abc NoMethodError: undefined method `abc' for TestFunctions:Module from (irb):4 

再次testing不了。

 defined?(TestFunctions::abc) #=> nil, but TestFunctions.method_defined? :abc #=> true 

就像我在顶部所说,我知道我是愚蠢的,任何人都可以让我愚蠢?

如果你想要Module级的function,可以用以下任何一种方式来定义它们:

 module Foo def self.method_one end def Foo.method_two end class << self def method_three end end end 

所有这些方法将使方法可用作为Foo.method_oneFoo::method_one

正如其他人所提到的, Module s中的实例方法是在包含Module的地方可用的方法

我会试着总结一下自己的各种答案,因为每个答案都有一些有价值的东西可以说,但是现在没有什么真正的答案可能是最好的答案:

我是在问错误的问题,因为我做错了。

由于我不能再解释的原因,我想在图书馆里有一套完全独立的function,它代表了我正试图从我的课堂上干的方法。 这可以通过使用类似的东西来实现

 module Foo def self.method_one end def Foo.method_two end class << self def method_three end end def method_four end module_function :method_four end 

我也可以include我的模块,或者在一个类中,在这种情况下,方法成为类的一部分或外部,在这种情况下,他们被定义在我正在运行的任何类(Object?Kernel?Irb,如果我互动?可能不是一个好主意,然后)

事情就是,没有理由不开始上课,我不知怎么就想到了一个让我一个很less使用和坦率地稍微奇怪的支线的思路。 可能是OO成为主stream之前的一个倒叙(我已经够老了,直到今天,我花了更多的时间编写程序代码)。

所以这些函数已经进入了一个类,看起来非常开心,并且这样暴露出来的类方法在必要时被愉快地使用。

你也可以像这样使用module_function:

 module TestFunctions def abc puts 123 end module_function :abc end TestFunctions.abc # => 123 

现在,您可以在课堂上包含TestFunctions,并从TestFunctions模块中调用“abc”。

我弄了一会儿,学了几样东西。 希望这会帮助别人。 我正在运行Rails 3.2.8。

我的模块(utilities.rb)看起来像这样,并在我的rails应用程序的/ lib目录中:

 module Utilities def compute_hello(input_string) return "Hello #{input_string}" end end 

我的testing(my_test.rb)如下所示,位于我的rails应用程序的/ test / unit目录下:

 require "test_helper" require "utilities" class MyTest < ActiveSupport::TestCase include Utilities def test_compute_hello x = compute_hello(input_string="Miles") print x assert x=="Hello Miles", "Incorrect Response" end end 

这里有几件事要注意:我的testing扩展了ActiveSupport :: TestCase。 这很重要,因为ActiveSupport将/ lib添加到$ LOAD_PATH中。 (seehttp://stackoverflow.com/questions/1073076/rails-lib-modules-and)

其次,我需要“需要”我的模块文件,也“包含”模块。 最后,需要注意的是,从模块中获取的东西实际上被放置在testing类中。 所以…要小心,包含的模块不能以“test_”开头。 否则,Rails会尝试运行你的模块方法作为testing。

你需要包含模块

include Testfunctions

那么'abc'会返回一些东西。

您不能直接在模块中调用方法。 你需要把它包含在一个类中。 尝试这个:

 >> class MyTest >> include TestFunctions >> end => MyTest >> MyTest.new.abc 123 => nil 

你需要在你的函数前加上模块名称,因为模块不是类:

你的/lib/test_functions.rb:

 module TestFunctions def TestFunctions.abc puts 123 end end 

你的代码使用模块方法:

 require 'test_functions' TestFunctions.abc