We recently made some enhancements to Clearance. One of those was to replace a manual process of the developer setting constants in their Rails environment files with a configuration block that could be used in config/initializers/clearance.rb.
I liked the way Hoptoad does it and wanted to implement the same pattern:
HoptoadNotifier.configure do |config|
config.api_key = 'your_key_here'
end
So let’s implement:
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
We have a configure class method that stores a Configuration object inside the Clearance module.
Anything application developers can set from their configure block is an attr_accessor on the Configuration class.
side note - I used the name mailer_sender to match the Devise API.
So now, we can have a config/initializers/clearance.rb:
Clearance.configure do |config|
config.mailer_sender = 'donotreply@example.com'
end
Easy for the application developer to understand. Cleaner implementation internally:
Clearance.configuration.mailer_sender
As an added bonus, in the library’s tests, we can set configuration attributes without worrying about undefining constants:
Clearance.configuration.mailer_sender= 'new.email@example.com'
Yay.

Shoulda