jeudi 13 août 2015

Ruby on Rails multiple classes with same name under different namespace

So I have some classes in Rails that do a bit of funky stuff. I have some classes under a Rails application named ApplicationName. They are autoloaded as part of Rails on the boot of my application server. Some are ActiveRecord models and some are just PORO models that are created to deal with some other stuff and some are service classes which are also PORO's. Some of these classes have the same name but are under different namespaces such as User and NameSpaced::User which represent different objects with similar concepts. In one of the namespaced classes I do some ETL work to get a foreign object to meld into an ActiveRecord model in my database. Since the ActiveRecord model by default is under the global ApplicationName namespace I figured ApplicationName::ModelName would work and I would be returned the top level object (the ActiveRecord model) I expected. Instead I got an unintialized constant error. If I do a ApplicationName::Application::ModelName I am able to return it but I get a warning about the class referencing the toplevel namespace (as I expected considering the ActiveRecord object resides up there). The ModelName model conflicts with another model under a different namespace (for the sake of argument we'll call it DifferentNameSpace). All in all things look like:

module ApplicationName
  class Application < Rails::Application
   # do autoload stuff here
  end
end

class ModelName
end

module DifferentNameSpace
  class ModelName
  end
end

Is there any way to specifically call ApplicationName::ModelName or to do an ApplicationName::Application::ModelName without the warning? Right now it works if I do ::ModelName but that looks so...ugly.

Aucun commentaire:

Enregistrer un commentaire