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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With