Config Block

Imagine using a third-party library in your Ruby program and configuring it like this:

Service.configure do |config|
  config.api_key = 'your_key_here'
  config.from = 'team@example.com'
end

How might it be implemented?

module Service
  def self.config
    @config ||= Config.new
  end

  def self.configure
    yield config
  end

  class Config
    attr_accessor :api_key, :from

    def initialize
      @api_key = ''
      @from = 'default@example.com'
    end
  end
end

The config class method stores a global Config object in the Service module.

Each config setting can be accessed like this:

Service.config.api_key