How to use ActiveSupport::Configurable with Rails

2019-02-15 11:47发布

问题:

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

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.

回答1:

The source file for ActiveSupport::Configurable got decent documentation: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/configurable.rb

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

Now I can configure the engine with this API:

MyGem.configure do |config|
  config.bar = 'baz'
end

And access the configuration with

MyGem.configuration.bar


回答2:

try this out

I hope this is simple and clear.

Example Code