I am working on releasing my first Gem for Rails. It is pretty simple, but I am needing to provide some access to setting config options. I'd like to have the user put something in 'config/initializers' and tie into that with my gem.
So, the question is: Is there a best-practice for providing config options in a Rails gem?
In an engine I help develop, Forem, we use mattr_accessors
on the top-level constant like this:
lib/forem.rb
module Forem
mattr_accessor :user_class, :theme, :formatter, :default_gravatar, :default_gravatar_image,
:user_profile_links, :email_from_address, :autocomplete_field,
:avatar_user_method, :per_page
...
Then inside config/initializers
we ask users to set them up like this:
Forem.user_class = 'User'
Forem.autocomplete_field = :login
With a short gem name, there's not much difference between this solution and the other one I will propose.
Solution #2
Still use mattr_accessors
on your top-level constant but offer a config
method on this module that takes a block and yields the object:
module ReallyComplicatedGemName
mattr_accessor :....
def self.config(&block)
yield(self)
end
...
This way people can do:
ReallyComplicatedGemName.config do |config|
config.user_class = "User"
...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With