How to dynamically load a class using namespaces / subdirectory in Ruby / Rails?

In my Rails 3.1 application (with Ruby 1.9), I have a Deployer1 class , which is in the working subdirectory below the model directory

I am trying to dynamically load / create this class using this code:

clazz = item.deployer_class # deployer_class is the class name in a string deployer_class = Object.const_get clazz deployer = deployer_class.new 

If I do not use namespaces, for example something global, for example:

 class Deployer1 end 

Then it works fine (deployer_class = "Deployer1") - it can load the class and create the object.

If I try to put it in a module to name a little space, like this:

 module Worker class Deployer1 end end 

It does not work (deployer_class = "Worker :: Deployer1") - it gives an error about a missing constant, which, in my opinion, means that it cannot find the class.

Usually I can access the class in my Rails code in a static way (Worker :: Deployer1.new) - so Rails is configured correctly to load this, maybe I am loading it incorrectly ...

EDIT: So, according to Vlad’s answer, the solution I chose is:

 deployer_class.constantize.new 

Thank you, Chris

+7
source share
2 answers

try instead of constantize :

 module Wtf class Damm end end #=> nil 'Wtf::Damm'.constantize #=> Wtf::Damm Object.const_get 'Wtf::Damm' #=> Wtf::Damm 
+15
source

Object does not know a constant named Worker::Deployer1 , therefore Object.const_get 'Worker::Deployer1' does not work. Object knows only the Worker constant. What works Worker.const_get 'Deployer1' .

Vlad Khomish's answer works because if you look at the implementation of constantize , this is exactly what it does: it breaks the string into '::' and recursively const_get .

+4
source

Source: https://habr.com/ru/post/898345/


All Articles