如何在 Rails 引擎中使用 ActiveSupport::Configurable

编程入门 行业动态 更新时间:2024-10-27 19:22:10
本文介绍了如何在 Rails 引擎中使用 ActiveSupport::Configurable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想给我的 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

本文发布于:2023-10-29 02:46:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:引擎   如何在   Configurable   Rails   ActiveSupport

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!