加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby顶级Contstant加载问题

发布时间:2020-12-17 02:22:47 所属栏目:百科 来源:网络整理
导读:我的Rails应用程序中有以下模型: class Comment class Digest endend 当我尝试在控制台中加载它时,我得到: $rails cLoading development environment (Rails 4.1.2)irb(main):001:0 Comment::Digest(irb):1: warning: toplevel constant Digest referenced
我的Rails应用程序中有以下模型:

class Comment
  class Digest
  end
end

当我尝试在控制台中加载它时,我得到:

$rails c
Loading development environment (Rails 4.1.2)
irb(main):001:0> Comment::Digest
(irb):1: warning: toplevel constant Digest referenced by Comment::Digest
=> Digest
irb(main):002:0> require "comment/digest"
=> true
irb(main):003:0> Comment::Digest
=> Comment::Digest

如果我将Digest的名称更改为Other,则可以正常工作.该课程用于摘要通知,如果我可以相对容易地解决它,我想保留名称.

class Comment
  class Other
  end
end

irb(main):003:0> Comment::Other
=> Comment::Other

如果我添加一个初始化程序来加载模型,它可以正常工作:

# config/initializers/comment_digest_loader.rb

require "comment"
require "comment/digest"

我意识到它没有使用const_get b / c加载,Digest模块已经存在.只是不确定处理这个的最佳方法.

解决方法

当您尝试引用存在于顶级但在引用常量中不存在的常量内的常量时,会收到错误:

Comment::String
# warning: toplevel constant String referenced by Comment::String

在尝试引用它之前,请确保声明了Comment :: Digest类.

更新:

似乎Rail的自动加载功能依赖于const_missing被调用,因为常量Digest已经存在于toplevel中,const_misssing显然没有被调用,并且抛出错误而不是被加载的类.

要验证这一点,请尝试运行代码而不要求摘要常量.

要缓解这种情况,您可以尝试急切加载模型:

Rails.application.eager_load!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读