MyGem.configure Block

We recently enhanced Clearance with a configuration block that could be used in config/initializers/clearance.rb.

I liked the way Airbrake did it and wanted to implement the same pattern:

Airbrake.configure do |config|
  config.api_key = 'your_key_here'
end

Here’s the implementation:

module Clearance
  class << self
    attr_accessor :configuration
  end

  def self.configure
    self.configuration ||= Configuration.new
    yield(configuration)
  end

  class Configuration
    attr_accessor :mailer_sender

    def initialize
      @mailer_sender = 'donotreply@example.com'
    end
  end
end

The configure class method stores a Configuration object inside the Clearance module.

Anything set from the configure block is an attr_accessor on the Configuration class.

So now config/initializers/clearance.rb is possible:

Clearance.configure do |config|
  config.mailer_sender = 'donotreply@example.com'
end

Easy for the application developer to understand. Clean internal implementation:

Clearance.configuration.mailer_sender

In the library’s tests, set configuration attributes without worrying about undefining constants:

Clearance.configuration.mailer_sender= 'new.email@example.com'

Yay.

spirograph

Sharpen your programming skills by completing coding exercises that are reviewed by other developers at Upcase today.