You might know a few examples, where you configure some library via a block. One example is the Rails configuration:
Rails.application.configure do |config|
  config.enable_reloading = false
end
This card describes a simple example on how to make your ruby library configurable.
Example
module FooClient
  class Client
    class_attribute :config
    def self.configure
      self.config ||= Configuration.new
      yield(config)
    end
    def test
      uri = URI.parse(FooClient::Client.config.endpoint)
      Net::HTTP.get_response(uri)
    end
  end
end
module FooClient
  class Configuration
    attr_accessor :endpoint
  end
end
With the code above you can send a get request with the following code:
FooClient::Client.configure do |config|
  config.endpoint = 'https://example.com'
end
FooClient::Client.new.test
Notes
- You can use 
  ActiveSupport::Configurable
  
    Show archive.org snapshot
  
 instead of the Configurationclass.
- When you are using Rails with Zeitwerk and the code for e.g. FooClientlives in a folder, that is loaded after the initializer, you need to write something like this:
Rails.autoloaders.main.on_load('FooClient::Client') do |client|
  client.configure do |config|
    config.endpoint = 'https://example.com'
  end
end
Posted by Emanuel to makandra dev (2024-07-31 09:49)