How to handle configuration for Rails Gem

I am working on the release of my first Gem for Rails. This is pretty simple, but I need to provide some access to the configuration settings. I would like the user to put something in "config / initializers" and bind it to my gem.

So the question is, is there a best practice for providing configuration options in a Rails stone?

+7
source share
1 answer

In the engine that helps me, Forem , we use mattr_accessors for a top-level constant, like this:

Library /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 install them as follows:

 Forem.user_class = 'User' Forem.autocomplete_field = :login 

With the short name of the pearl, there is not much difference between this solution and the other proposal that I will offer.


Decision number 2

Continue to use mattr_accessors in your top-level constant, but suggest a config method in this module that takes a block and gives an 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 
+11
source

All Articles