Skip to content

Instantly share code, notes, and snippets.

@kamilio
Last active December 21, 2015 00:19
Show Gist options
  • Save kamilio/6219628 to your computer and use it in GitHub Desktop.
Save kamilio/6219628 to your computer and use it in GitHub Desktop.

How to configure gems

Are you writing a new gem and you are not sure how to let user configure it? Here is a short gist to show you how to do it. I like this style of configurations, inspired by many already existing gems such as Devise, Airbrake, PDFkit and many more.

# Configuration
MyShinyGem.configure do |config|
  config.binary = '/bin/ls'
  config.username = 'superuser'
  config.password = 'superpassword'
end
MyShinyGem.configuration.binary
MyShinyGem.configuration.username

Implementation

Implemenation of this pattern is very simple and requires only few lines of code. Firstly define two class methods on your top level module allowing you to configure and access the configuration

# lib/my_shiny_gem.rb
module MyShinyGem
  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.configure
    yield(configuration)
  end
end

Secondly create a simple class defining your configuration attributes and their default values.

# lib/my_shiny_gem/configuration.rb
class MyShinyGem::Configuration
  attr_accessor :binary, :username, :password
  def initialize
    # You can put your default values here
    self.binary = '/bin/df'
  end
end

Happy gem configurations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment