23 Juluninitialized constant MyModule::MyClass in Rails 3

Saturday, 23 July 2011 — 23:02

If you ended up in this blog because of the exception uninitialized constant MyModule::MyClass on a Rails 3 application i hope you can find the solution here.

The error message is self explanatory. What is not that obvious is where the problem is. Basically, the Rails is not able to find your class.

The first thing you should check, is its name, and folder/s containing your class. For instance, if you have something like this (myclass.rb):

module MyModule
    class MyClass;  end
end

you can call MyClass in this way:

MyModule::MyClass.new

so far, so good. But there can be situations, where this will not work. Take into account this schema:

/lib
  /my_module
    klass1.rb
    ...
    utils.rb
  /utils
    klass2.rb

Next code in klass1.rb will fail:

def do_something
  Utils::Klass2.new
end

As you are in Utils class, it tries to find Klass2 constant in that scope, and obviously can’t find it. I guess you got it. To fix these situations, you have 2 options. Change the name of your modules/files, or use :: to reference root (you’d better go through first approach for a more stable solution though):

def do_something
  ::Utils::Klass2.new
end

However, this is not the problem on most of the cases. Did you enable autoload paths in config/application.rb file?. If you want to autoload your classes under lib directory, make sure you have something like this (config/application.rb):

# Custom directories with classes and modules you want to be autoloadable.
    config.autoload_paths += %W(#{config.root}/lib)

And finally, if anything before fixed your problem, make sure you restart your server :)

Ger

Comentarios

Añade tu comentario




(textile habilitado)
Negrita: *Google*
Enlace: "google.com":http://www.google.com
Imagen: !http://ggomeze.com/images/avatar.png!

ó Cancelar