Reputation: 453
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?
Upvotes: 1
Views: 1155
Reputation: 34774
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.
Upvotes: 3
Reputation: 1750
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:
curation
or rename the module to GalleryCuration
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
Upvotes: 4