【问题标题】:Bundler.require does not work for ActiveRecord in my gemBundler.require 不适用于我的 gem 中的 ActiveRecord
【发布时间】:2010-10-25 16:52:44
【问题描述】:

我刚刚创建了一个新 gem(使用 bundler)并想添加 Active Record 支持。所以我在我的 gemspec 中添加了s.add_dependency "activerecord", "~> 3.0"。然后我使用 Bundler.setup 和 Bundler.require 并认为我现在可以访问 Active Record,但我没有。我必须明确使用require "active_record"。知道为什么 Bundler.require 在这种情况下对我不起作用吗?

【问题讨论】:

    标签: ruby-on-rails ruby gem bundler


    【解决方案1】:

    首先,如果您要打包一个 gem,do not use Bundler.require。 Bundler.require 用于应用而非宝石。

    • 在.gemspec 中,指定已部署gem 的依赖项。

    • 在您的Gemfile 中,包含gemspec 行以自动将您的.gemspec 中列出的依赖项包含在您的Gemfile 中。

      您还可以选择为开发和测试创建 gem 组。

    • 在您的代码中,明确地require 任何您需要的库。

    我今天在这件事上浪费了几个小时,所以我希望这会有所帮助。

    (来源1,2)

    其次,虽然 ActiveRecord gem 被称为“activerecord”,但 lib 被称为“active_record”。这就是您在Gemfile 中所需要的。

    gem 'activerecord', :require => "active_record"
    

    除非您包含 :require 选项,否则 ActiveRecord 将无法正确加载,并且您在尝试使用它之前不会知道它。

    【讨论】:

      【解决方案2】:

      如果你想使用 Bundler,你需要用 Activerecord 定义你的 Gemfile

      gem 'activerecord', "~> 3.0.0"
      

      或者您需要定义捆绑器来使用您的 gemspec,并在您的 Gemfile 中添加 gemspec

      gemspec
      

      见http://gembundler.com/rubygems.html

      【讨论】:

      • 我的 Gemfile 中已经有 gemspec(捆绑程序会自动为新创建的 gem 执行此操作),所以这不是问题。
      【解决方案3】:

      我遇到了这个问题,我的问题是我在我的 gem 活动记录中命名了一个目录,如下所示:

      lib ->
        active_record ->
          base.rb <- containing some monkey patches to base
      

      这引起了巨大的混乱,包括像这样的甜蜜错误消息:

      Gem Load Error is: uninitialized constant ActiveRecord::Base
      Did you mean?  ActiveRecord::Base
      

      只需将文件从 lib/active_record/base.rb 更改为 lib/active_record_base.rb 即可为我修复它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-10-29
        • 1970-01-01
        相关资源
        最近更新 更多