【发布时间】:2016-02-12 14:55:36
【问题描述】:
在您将此问题标记为重复之前,我已经检查了其他非常相关的问题:1、2、3、4 和 5,基本上,它们都是相同的加载lib 模块的方法,但User 仍然不断抛出错误。
models/user.rb
# This line throws an error:
# cannot load such file -- my-project-root/lib/model_with_properties.rb
require "#{Rails.root}/lib/model_with_properties.rb"
class User < ActiveRecord::Base
# This line throws an error:
# uninitialized constant User::ModelWithProperties
include ModelWithProperties
...
end
lib/model_with_properties.rb
module ModelWithProperties
# Some functions
end
config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'yaml'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Project
class Application < Rails::Application
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Load the lib folder, a thousand times
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths << "#{Rails.root}/lib"
end
end
我错过了什么?
另一个有用的信息:
julian$ rails r 'puts ActiveSupport::Dependencies.autoload_paths'
Running via Spring preloader in process 38445
/my-project-root/lib
/my-project-root/lib/
/my-project-root/lib/assets/
/my-project-root/lib/tasks/
/my-project-root/app/assets
/my-project-root/app/controllers
/my-project-root/app/helpers
/my-project-root/app/jobs
/my-project-root/app/mailers
/my-project-root/app/models
/my-project-root/app/controllers/concerns
/my-project-root/app/models/concerns
/my-project-root/test/mailers/previews
julian$ rails -v
Rails 4.2.3
回答
非常感谢@jvillian,我使用的是 RubyMine,我认为文件扩展名是隐藏的,而重要的是 IDE 上的 Ruby 图标。实际上缺少.rb 扩展。
【问题讨论】:
-
呃!在过去的几天里,我一直在与 AutoLoading Constants 搏斗。不太好。如果你在控制台中,当你
require 'model_with_properties'时你会得到什么? -
要么将
lib添加到您的自动加载路径中,要么将require手动添加到文件中,而不是同时添加。 -
有时,需要重新加载 Spring。尝试运行
spring stop并重新启动您的应用程序。 -
您确定该文件在 lib 目录中并且具有 .rb 扩展名吗?抱歉问了这么愚蠢的问题,但
Dir["lib/**/*.rb"] => []很好奇。 -
@jvillian 就是这样。我觉得自己太笨了,我没有注意到。 IDE 显示 ruby 图标:/ 更新了问题。如果您想发布答案,我会选择它。非常感谢。
标签: ruby-on-rails ruby module