Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing Error: Uninitialized constant in Rails 3

I have a file containing a helper class something like this:

app/classes/myfile.rb

Module mymodule
  class myclass
    # blah blah
  end
end

I want to use this class in a controller, so I wrote something like this:

require 'myfile'

class MyController < ApplicationController

  include mymodule  

  def index
    mymodule::myclass.new
  end

end

The route for the controller is defined like this:

  match 'mycontroller', :to => 'mycontroller#index'

Now for the strange behaviour I'm facing. It works perfectly fine on the first run after the server starts. But when I refresh the page or hit the URL again, I get the following error.

Routing Error

uninitialized constant MyController::mymodule

I cannot make out anything out of the error, nor can I understand why it does not work from the second hit onward only. What's happening?

like image 990
akula1001 Avatar asked Sep 03 '10 08:09

akula1001


2 Answers

Generally speaking, Rails likes to see files containing:

module MyModule

named my_module.rb

Modules are generally capitalized

Also, it thinks that MyModule is scoped under the MyController class, which it is not. You could try

include ::MyModule 

to access it from the top-level scope.

I also don't know if your load paths include your classes directory, so it is probably not autoloading the myfile.rb file in the first place.

like image 136
Lukas Avatar answered Oct 18 '22 00:10

Lukas


I changed require 'myfile' to load 'myfile.rb' and it now works fine. I don't know if I solved the problem though. I don't know what is happening. Can someone enlighten me?

like image 29
akula1001 Avatar answered Oct 18 '22 01:10

akula1001