Simplest configuration block implementation for a ruby gem ever

For my own gems, I want to have a configuration block, which usually looks like this:

Yourgem.configure do |config|
  config.some_config = "foobarbaz"
end

There are a lot of articles how to implement this functionality:

Isn’t it still looks too complicated? Can’t be a configuration object just a plain ruby hash?

Yes, it can:

module Yourgem
  def self.configuration
    @configuration ||= {}
  end

  def self.configure
    yield(configuration)
  end
end

And now:

Yourgem.configure do |config|
  config[:some_config] = "foobarbaz"
end

Yourgem.configuration # => { :some_config => "foobarbaz" }
Yourgem.configuration[:some_config] #=> "foobarbaz"

Looks clean and simple, but there is one restriction: instead of classy Yourgem.configuration.some_config we have to act with it like with hash (because configuration value it’s a hash): Yourgem.configuration[:some_config]. To solve this problem, we’ll use Ruby’s built-in OpenStruct:

require 'ostruct'

module Yourgem
  def self.configuration
    @configuration ||= OpenStruct.new
  end

  def self.configure
    yield(configuration)
  end
end

And now:

Yourgem.configure do |config|
  config.some_config = "foobarbaz"
end

Yourgem.configuration # => #<OpenStruct some_config="foobarbaz">
Yourgem.configuration.some_config #=> "foobarbaz"

Clean and simple.

Comments at Medium.