Cyril Duchon-Doris Cyril Duchon-Doris - 2 months ago 17
Ruby Question

Rails - Get namespaced constant from Rails configuration

Suppose I have several implementations for a search engine.

module Searcher
module Engine
class Elasticsearch
end

class Algolia
end
end
end


I want a per-environment search engine configuration.

I declared the config in my environment (for some sort of Bridge Pattern)

Rails.application.configure do
config.search_engine = :elasticsearch
end


(Which I override in specific environment files)

Then in my search controller, I want to load the appropriate class according to the symbol I put in Rails.configuration.search_engine

@search_engine = Searcher::Engine::XXX
@search_engine.search


How do I resolve the full namespaced constant
Searcher::Engine::XXX
from the symbol
:elasticsearch
?

EDIT :

Searcher::Engine.const_get(Rails.configuration.search_engine.to_s.titleize)


Does not work : it loads
Elasticsearch
(from the gem) and not
Searcher::Engine::Elasticsearch
(my own component)

::Searcher::Engine::Elasticsearch # => Searcher::Engine::Elasticsearch
Searcher::Engine.const_get(Rails.configuration.search_engine.to_s.titleize) # => Elasticsearch
Object.const_get("::Searcher::Engine::#{Rails.configuration.search_engine.to_s.titleize}") # => Elasticsearch


Ruby 2.3.0
Rails 5

Answer

Assuming your search engines are all under ::Searcher::Engine:

"::Searcher::Engine::#{Rails.configuration.search_engine.to_s.titleize}".constantize