Configuration pattern in Ruby

Sometimes you need to add flexibility to your code and this pattern is a simple and clear way to accomplish this.It is widely used in gems also.

This is how it’s used:

Zuper.configure do |config|
  config.name = 'ACME'
  config.platform = 'Unix'
end

You can then access the values:

Zuper.configuration.name
Zuper.configuration.platform

And this is the implementation:

module Zuper
  class Configuration
    attr_accessor :name, :platform
  end

  class << self
    attr_writer :configuration
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.configure
    yield configuration
  end
end