3

我正在尝试扩展核心类,但不知道为什么在通过 Rails 4 控制台调用时会失败:

# config/application.rb
config.autoload_paths += Dir["#{config.root}/lib/**/"]

# lib/core_ext/string.rb
class String
  def test
    self + " some test"
  end
end

# lib/core_ext/array.rb
class Array
  def mean
    sum / size if sum && size
  end
end

# lib/core_ext/test.rb
class Test
  def test
    "some test"
  end
end

Rails 控制台输出:

1] pry(main)> test = Test.new
#<Test:0x007ff63971b588>
[2] pry(main)> test.test
"some test"
[3] pry(main)> "string".test
NoMethodError: private method `test' called for "string":String
from (pry):3:in `__pry__'
[4] pry(main)> [1,2,3].mean
NoMethodError: undefined method `mean' for [1, 2, 3]:Array
from (pry):4:in `__pry__'
4

3 回答 3

4

您应该添加以下行以有效地将文件要求到您的项目中

Dir[File.join(Rails.root, "lib", "core_ext", "*.rb")].each {|l| require l }

取自In Ruby on Rails,扩展 String 类,代码应该放在哪里?

于 2013-08-13T01:20:21.430 回答
3

我会添加以下内容:

# In config/initializers/require.rb:
require "core_ext/string" 
require "core_ext/array" 
require "core_ext/test"

并且不要修改 config/application.rb 的 autoload_paths,它不会急切加载您的扩展。如果模块或类已经加载到其他地方,它不会扩展它。如需参考,请查看这些 SO question1question2

于 2015-07-29T19:09:55.690 回答
1

请注意,如果您对静态方法(例如String.test)感兴趣,您可以将其声明为def self.test.

于 2014-02-13T12:18:23.010 回答