5

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.

antpaw
  • 15,444
  • 11
  • 59
  • 88

2 Answers2

15

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
Arctodus
  • 5,743
  • 3
  • 32
  • 44
  • Thanks, https://github.com/antpaw/bhf/blob/master/lib/bhf.rb i couldn't figure out the yield part – antpaw Jun 11 '14 at 16:53
-3

try this out

I hope this is simple and clear.

Example Code

Sachin Singh
  • 7,107
  • 6
  • 40
  • 80