我想给我的 rails engine gem 一个合适的配置可能性.在 initializers/my_gem.rb 中看起来像这样的东西 (链接到当前初始化程序):
I want to give my rails engine gem a proper configuration possibilities. Something that looks like this in initializers/my_gem.rb (link to the current initializer):
MyGem.configure do |config| config.awesome_var = true # config.param_name = :page end所以我四处寻找其他 gem 中的任何线索,我找到的最好的就是这个 kaminari/config.rb.但它看起来太hacky了,我认为一定有更好的方法.
So I've looked around for any clues in other gems and the best I cloud find was this kaminari/config.rb. But it looks so hacky that I think there must be a better way.
推荐答案ActiveSupport::Configurable 的源文件得到了不错的文档:github/rails/rails/blob/master/activesupport/lib/active_support/configurable.rb
The source file for ActiveSupport::Configurable got decent documentation: github/rails/rails/blob/master/activesupport/lib/active_support/configurable.rb
我喜欢将配置放入引擎中它自己的类中(就像 kaminari 那样):
I like to put the configuration into it's own class within the engine (like kaminari does):
class MyGem def self.configuration @configuration ||= Configuration.new end def self.configure yield configuration end end class MyGem::Configuration include ActiveSupport::Configurable config_accessor(:foo) { "use a block to set default value" } config_accessor(:bar) # no default (nil) end现在我可以用这个 API 配置引擎了:
Now I can configure the engine with this API:
MyGem.configure do |config| config.bar = 'baz' end并使用
MyGem.configuration.bar更多推荐
如何在 Rails 引擎中使用 ActiveSupport::Configurable
发布评论