Cannon Moyer
Cannon Moyer

Reputation: 3164

Reference Constant as String

In my /lib directory in Rails 5, I have a class that is within the namespace of a Ruby module.

I can reference the class with the following code:

OrderSyncers::Marketplaces::Walmart.new

In my Rails model I have a marketplace column that contains a marketplace name such as "Walmart". I am trying to reference the Walmart class. Note: the Walmart class is a subclass of OrderSyncers::OrderSync.new.

In ruby I can successfully call a class with the following code:

Object.cont_get("Test").new

However, when I try to reference that class name within the namespace reference, I get an error.

OrderSyncers::Marketplaces::Object.const_get("Walmart").new

Error:

NameError (uninitialized constant OrderSyncers::Marketplaces::Object)

The reason I am wanting to use Object.const_get("string") is so that I can use the fields I have in my database to initialize the correct subclass of OrderSyncers::OrderSync.

Upvotes: 1

Views: 103

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Why did you add the ::Object? You don't need it.

OrderSyncers::Marketplaces.const_get("Walmart").new

Upvotes: 3

Related Questions