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
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