【问题标题】:Rails 3 problem loading classes from lib in config/environments/development.rbRails 3 问题从 config/environments/development.rb 中的 lib 加载类
【发布时间】:2011-09-12 21:32:19
【问题描述】:

我正在将 Rails 2.3.11 应用程序升级到 3.0.10。当我尝试运行rails console 之类的任何rails 脚本或运行我的单元测试时,我在development.rb 文件中得到了NameError

我正在调用我在lib 中定义的类,但是当development.rb 调用该类时,似乎还没有加载库。

我正在做类似的事情:

config.cache_store = CustomMemcachedStore.new(Memcached.new(...))

我有一个文件lib/custom_memcached_store.rb 声明了这个类

class CustomMemcachedStore < ActiveSupport::Cache::Store

我收到以下错误:

~/.rvm/gems/ruby-1.9.2-p290/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing': uninitialized constant CustomMemcachedStore (NameError)
    from ~/app_name/config/environments/development.rb:20:in `block in <top (required)>'

application.rb,我已经在使用了

config.autoload_paths += Dir["#{Rails.root}/lib"]

感谢您能给我的任何帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rails-3-upgrade


    【解决方案1】:

    您需要明确地require 文件,而不是依赖自动加载。

    这是因为环境配置的加载发生在启动过程的早期,在设置自动加载路径之前。

    在某些情况下,您可以使用初始化程序将配置代码插入到有效的位置,例如:

    initializer "my_setup", :before => "some_other_setup" do |app|
      # ...
    end
    

    不幸的是,这不是其中一种情况,因为缓存设置为here,而自动加载路径直到here 才设置,紧挨在boostrap_hook 之前。

    【讨论】:

    • 谢谢,需要修复它。非常感谢您使用 bootstrap.rb 中的代码解释原因,而不仅仅是告诉我使用 require。
    • 很高兴为您提供帮助。我必须查一下以确定初始化程序的顺序,所以我们都学到了一些东西:-)
    猜你喜欢
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多