Rails - 从 Rails 配置中获取命名空间常量 [英] 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)
然后在我的搜索控制器中,我想根据我在 Rails.configuration.search_engine 中放置的符号加载相应的类
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
如何从符号 :elasticsearch
解析完整的命名空间常量 Searcher::Engine::XXX
?
How do I resolve the full namespaced constant Searcher::Engine::XXX
from the symbol :elasticsearch
?
Searcher::Engine.const_get(Rails.configuration.search_engine.to_s.titleize)
不起作用:它加载 Elasticsearch
(来自 gem)而不是 Searcher::Engine::Elasticsearch
(我自己的组件)
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
红宝石 2.3.0导轨 5
Ruby 2.3.0 Rails 5
推荐答案
假设你的搜索引擎都在 ::Searcher::Engine
下:
Assuming your search engines are all under ::Searcher::Engine
:
"::Searcher::Engine::#{Rails.configuration.search_engine.to_s.titleize}".constantize
这篇关于Rails - 从 Rails 配置中获取命名空间常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!