Calling a class with names with the Rails constant of the inflector

I have a class that needs to be initialized, but these names are placed as follows:

SomeThing::MyClass.new() 

But I am calling it from args in a rake task, so it goes in line:

 task :blah, [:my_class_name] => :environment do |t, args| class_name = args[:my_class_name].camelize.constantize puts class_name end 

So, obviously, if I call the rake command as follows:

 rake blah[my_class] 

My task returns:

 MyClass # <= Actual ruby object 

But how can I get it to run from a namespace chained to another method, for example:

 SomeThing::MyClass.new() 

From the string provided as input?

+4
source share
1 answer

You can make your life easier by simply using the class name string and making

 Something.const_get(args[:my_class_name]).new 

Here's a simplified version (regular IRB, no Rails):

 module Something ; end class Something::MyClass ; end my_class_name = "MyClass" Something.const_get(my_class_name).new #=> #<Something::MyClass:0x007fa8c4122dd8> 
+8
source

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


All Articles