如何使用ActiveSupport :: Configurable与Rails引擎 [英] How to use ActiveSupport::Configurable with Rails Engine

查看:179
本文介绍了如何使用ActiveSupport :: Configurable与Rails引擎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


$ b b

所以我一直在寻找其他宝石中的任何线索,最好的云发现是这 kaminari / config.rb
但是它看起来很黑,我认为一定有更好的方法。

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 获得体面的文档:
https://github.com/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

这篇关于如何使用ActiveSupport :: Configurable与Rails引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆