从 lib 文件夹加载文件的最佳方法是什么,这些文件将方法添加到 Rails 3 中的 ~existing~ 类? [英] What is the best way to load files from the lib folder that add methods to ~existing~ classes in Rails 3?

查看:40
本文介绍了从 lib 文件夹加载文件的最佳方法是什么,这些文件将方法添加到 Rails 3 中的 ~existing~ 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以与此非常相似的方式使用 config.autoload_paths 相关问题 从 Rails 3 项目的 lib 目录加载类.

I am using config.autoload_paths in a way very similar to this related question to load classes from the lib directory in a Rails 3 project.

具体来说,我已将这些行添加到 config/application.rb 文件中:

Specifically, I've added these lines to the config/application.rb file:

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

但是,对于现有类,此方法对我不起作用.当我添加像 lib/extensions/string.rb 这样的文件时:

However, this method is not working for me for existing classes. When I add a file like lib/extensions/string.rb:

class String
  def foo
    puts "foo"
  end
end

我收到一个 未定义的方法 'foo' for "":String 错误.通过各种搜索,我感觉到这个问题与这些文件的延迟加载有关.我尝试使用 config.eager_load_paths 但无法让它工作.

I get an undefined method 'foo' for "":Stringerror. Through various searches I've got the sense that this problem has to do with the lazy loading of these files. I tried using config.eager_load_paths but was not able to get that to work.

推荐答案

我正在完全做你在我的申请中描述的事情,唯一的区别是我em> 有一个名为 extensions.rb 的初始化程序,代码如下:

I'm doing exactly what you are describing in my application, and the only difference is that I also have an initializer called extensions.rb with the following code:

Dir.glob('lib/extensions/*').each { |f| require f }

这篇关于从 lib 文件夹加载文件的最佳方法是什么,这些文件将方法添加到 Rails 3 中的 ~existing~ 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆