1

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?

user1618840
  • 453
  • 1
  • 5
  • 14
  • Check this post , that could help you : http://stackoverflow.com/questions/9011624/including-modules-and-classes-in-rails – Tanguy S Apr 24 '15 at 12:37
  • It would be helpful it you show the code for Curation module and what's the path/file_name of the file you put it. – Piotr Jakubowski Apr 24 '15 at 12:47
  • @TanguyS in that question, the dev is trying to include inside a module – user1618840 Apr 24 '15 at 13:35
  • @PiotrJakubowski the filepath for the Curation module is app/gallery_curation.rb. Curation code is just of the form: module Curation def method1 .... end .... end – user1618840 Apr 24 '15 at 13:35

2 Answers2

4

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

Piotr Jakubowski
  • 1,760
  • 10
  • 16
3

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.

Shadwell
  • 34,314
  • 14
  • 94
  • 99