简体   繁体   English

Rails:无法在类中包含模块

[英]Rails: Unable to include module in Class

I've defined a module in a file directly in my app folder, but am unable to use its methods in an ActiveRecord class (methods not recognized). 我已经在我的应用文件夹中的文件中直接定义了一个模块,但是无法在ActiveRecord类中使用其方法(无法识别方法)。 As I understand it, files in the app folder are supposed to be required automatically by rails. 据我了解,应用文件夹中的文件应该是Rails自动需要的。

I've also tried to include it manually: 我也尝试过手动添加它:

class Picture < ActiveRecord::Base
    include Curation
    ...
end

but I get 但我明白了

NameError: uninitialized constant Picture::Curation 

Am I mistaken about this, and actually do need to manually require all new files? 我是否对此感到误解,实际上确实需要手动要求所有新文件?

Rails does not require all the files from app in development mode. Rails不需要在开发模式下来自应用程序的所有文件。 Instead it loads the files on demand when you reference the constant that is undefined. 相反,当您引用未定义的常量时,它将按需加载文件。 Then it guesses the filename from the name of the Class or Module. 然后,它从类或模块的名称中猜测文件名。 In your case you have a Curation module defined in gallery_curation file. 在您的情况下,您在gallery_curation文件中定义了一个Curation模块。 When Rails notices Curation module that is undefined it is looking for curation.rb file in all subdirectories of app . 当Rails注意到未定义的Curation模块时,它将在app所有子目录中查找curation.rb文件。 Obviously the file can't be found, hence the exception. 显然找不到该文件,因此是一个例外。

You have 3 choices: 您有3种选择:

  1. go with Rails' convention and either rename your file to curation or rename the module to GalleryCuration 遵循Rails的约定,将文件重命名为curation或将模块重命名为GalleryCuration
  2. go with custom require_dependency 使用自定义的require_dependency
  3. set up an autoload path for Curation somewhere in your initializers. 在初始值设定Curation某个位置设置Curation的自动加载路径。

For your sanity, going with convention is recommended. 为了您的理智,建议您遵循约定。

More info about Rails autoloading here: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html 有关Rails自动加载的更多信息,请访问: http : //guides.rubyonrails.org/autoloading_and_reloading_constants.html

Rails doesn't autoload from the app directory itself. Rails不会从app目录本身自动加载。 If it's a module that is used in models only you could put it in the app/models directory (it doesn't matter that it's not actually a model). 如果仅是模型中使用的模块,则可以将其放在app/models目录中(没关系,它实际上不是模型)。 Alternatively if it is used in different types of classes you may be better putting it in lib . 另外,如果将它用于不同类型的类中,则最好将其放在lib

Additionally, rails autoloading only works when rails can correctly guess the name of the file that the constant (module in this case) will be included in. 此外,仅当rails可以正确猜测常量(在此情况下为模块)将包含在其中的文件名时,rails自动加载才有效。

This means that you'll need to call your file curation.rb for rails to autoload the Curation module from it. 这意味着您需要调用curation.rb文件以使Rails从中自动加载Curation模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM