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 fo开发者_开发问答r 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?
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.
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?
精彩评论