Rails - Get namespaced constant from Rails configuration

邮差的信 提交于 2020-01-05 05:30:30

问题


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


回答1:


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

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


来源:https://stackoverflow.com/questions/39698466/rails-get-namespaced-constant-from-rails-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!