Ruby: How to make your ruby library configurable

Updated . Posted . Visible to the public.

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

Rails.autoloaders.main.on_load('FooClient::Client') do |client|
  client.configure do |config|
    config.endpoint = 'https://example.com'
  end
end
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2024-07-31 09:49)