简体   繁体   中英

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). As I understand it, files in the app folder are supposed to be required automatically by 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. 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. When Rails notices Curation module that is undefined it is looking for curation.rb file in all subdirectories of app . Obviously the file can't be found, hence the exception.

You have 3 choices:

  1. go with Rails' convention and either rename your file to curation or rename the module to GalleryCuration
  2. go with custom require_dependency
  3. set up an autoload path for Curation somewhere in your initializers.

For your sanity, going with convention is recommended.

More info about Rails autoloading here: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html

Rails doesn't autoload from the app directory itself. 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). Alternatively if it is used in different types of classes you may be better putting it in 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.

This means that you'll need to call your file curation.rb for rails to autoload the Curation module from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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