简体   繁体   中英

Ruby - Accessing class that is not in the current scope?

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM