How to use ActiveSupport::Configurable with Rails Engine

天涯浪子 提交于 2019-11-30 19:30:01

问题


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



来源:https://stackoverflow.com/questions/24104246/how-to-use-activesupportconfigurable-with-rails-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!