无法扩展核心类

时间:2013-08-13 01:03:47

标签: ruby-on-rails ruby

我正在尝试扩展核心类,并且不知道为什么在通过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__'

3 个答案:

答案 0 :(得分:4)

您应该添加以下行以有效地要求文件进入您的项目

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

取自In Ruby on Rails, to extend the String class, where should the code be put in?

答案 1 :(得分: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

答案 2 :(得分:1)

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