Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a namespaced class with Rails constantize inflector

I have a class that needs to be initialized but it's namespaced like this:

SomeThing::MyClass.new()

But I'm calling it from the args in a rake task, so it comes in as a string:

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 task like this:

rake blah[my_class]

My task returns:

MyClass # <= Actual ruby object

But how can I get it to run from within a namespace chained before another method, like this:

SomeThing::MyClass.new()

From a string provided as the input?

like image 799
JP Silvashy Avatar asked Mar 21 '12 07:03

JP Silvashy


1 Answers

You can make your life easier by just using the string of the class name and doing

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

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

module Something ; end
class Something::MyClass ; end
my_class_name = "MyClass"
Something.const_get(my_class_name).new 
#=> #<Something::MyClass:0x007fa8c4122dd8>
like image 110
Michael Kohl Avatar answered Nov 11 '22 22:11

Michael Kohl