Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle config for Rails Gem

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?

like image 253
Matt Fordham Avatar asked Apr 18 '12 17:04

Matt Fordham


1 Answers

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
like image 92
Ryan Bigg Avatar answered Oct 16 '22 08:10

Ryan Bigg