Rails 3 - 我是否使配置文件太复杂了?
我是一个简单的人 - 我只想要一个可从控制器访问的 YAML 配置文件。就这样。
首先,我创建了 config/app_config.yml,其中包含我想要的配置值。到目前为止,一切都很好。
然后,我创建了 lib/app_config.rb
,其中包含:
module AppConfig
def self.config
@@config ||= {}
end
def self.config=(config)
@@config = config
end
end
最后,我创建了 config/initializers/load_app_config.rb
,其中包含:
# the ./ is necessary for some reason, though no examples online use it...
require './lib/app_config'
AppConfig.config = YAML.load_file("#{Rails.root.to_s}/config/app_config.yml")
我应该跳过 load_app_config .rb
一起,并以其他方式分配 AppConfig.config
(可能在模块本身内部)?
看来我把事情搞得太复杂了..
I'm a simple guy— I just want a YAML config file that's accessible from controllers. That's all.
First, I created config/app_config.yml
, which contains the config values I want. So far, so good.
Then, in I created lib/app_config.rb
, which contains:
module AppConfig
def self.config
@@config ||= {}
end
def self.config=(config)
@@config = config
end
end
Finally, I created config/initializers/load_app_config.rb
, which contains:
# the ./ is necessary for some reason, though no examples online use it...
require './lib/app_config'
AppConfig.config = YAML.load_file("#{Rails.root.to_s}/config/app_config.yml")
Should I skip load_app_config.rb
altogether, and assign AppConfig.config
some other way (perhaps inside of the module itself)?
It seems I'm making it too complicated..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用 Mark Bates 的 configatron,它与 AppConfig 方法相同,但它允许在 YAML 中使用 ERB 和可以帮助使用命名空间:
I use configatron by Mark Bates, it's the same as AppConfig approach, but it allows to use ERB in YAML and can help to use namespaces:
你让它变得比需要的更复杂一些。你只需要两件事:
你的配置:/config/config.yml
(应该看起来像这样,当然这些只是占位符)
然后你的初始化程序:/config/initializers/app_config.rb
现在你可以通过 AppConfig 从任何地方访问你的配置中的任何内容。例如,要在您所处的任何环境中获取主机名:
如果我们在本地运行,该值将是“localhost:3000”
You are making it a little more complicated than it needs to be. You only need 2 things:
Your conifg: /config/config.yml
(should look something like this, of course these are just placeholders)
Then your initializer: /config/initializers/app_config.rb
Now you can access anything from you config from anywhere via AppConfig. For example to grab the host name in whatever environment you are in would be:
If we were running locally, that value would be "localhost:3000"