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