Reputation: 63
Given two model that are namespaced as
SomeModule::V1::Api
SomeModule::V2::Api
I want to make a call in my controller like:
api = SomeModule::V1::Api
but have the "V1" portion be a variable, so that I can swap between versions.
Any ideas on how to make that happen?
Upvotes: 0
Views: 47
Reputation: 62668
If you don't want to use #constantize
(which is a part of ActiveSupport), you can do it with Plain Old Ruby:
version = "V1"
SomeModule.const_get(version).const_get("Api")
# => SomeModule::V1::Api
Upvotes: 1
Reputation: 160211
v = 'V1'
"SomeModule::#{v}::Api".constantize
=> SomeModule::V1::Api
Example:
module SomeModule
module V1; end
module V2; end
end
class SomeModule::V1::Api
def self.foo; 'V1 foo'; end
end
class SomeModule::V2::Api
def self.foo; 'V2 foo'; end
end
v = 'V1'
puts "SomeModule::#{v}::Api".constantize.foo
=> V1 foo
v = 'V2'
puts "SomeModule::#{v}::Api".constantize.foo
=> V2 foo
Upvotes: 1