Reputation: 77596
I have 2 classes
MyController
which is under app/controllers/api
MyManager
which is under libs/managers
I am trying to use this manager class from my controller and I'm getting the following error.
Uninitialized constant API::MyController::MyManager
How do I reference and use MyManager class from MyController class?
Controller
class API::MyController < API::BaseController
before_action :setup
def something
@myManager.doSomething
end
def setup
# Exception is thrown here
@myManager = MyManager.new
end
end
Manager
class MyManager
def doSomething
puts('something')
end
end
Upvotes: 0
Views: 92
Reputation: 154
Make sure you autoloaded the lib/managers directory:
# in config/application.rb
config.autoload_paths += %W(#{config.root}/lib/managers)
If MyManager is a Class (not a module) then you can just call MyManager.new without any problem.
Also just a note. In Rails 4 there are a couple of 'concerns' directories added under app/controllers and app/models (app/controllers/concerns and app/models/concerns). Any files under these directories will be autoloaded. By standards, only model related concerns (be it modules or classes) will be placed under app/models/concerns (same applies for controller related concerns).
Upvotes: 1
Reputation: 3329
This has to do with the way rails loads modules, take a look at this
I think what you want is to make sure your autoloading the lib directory and then call ::MyManager.method
since its trying to get the module from the Controller context.
::Module
indicates the absolute module.
Upvotes: 0