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:

- Ruby Gem Configuration Patterns

- MyGem.configure Block

- Creating a configurable Ruby gem

- RubyGem Configuration Pattern

- The easiest configuration block for your Ruby gems

- Ruby Gem Configuration Pattern

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

Yes, it can:



def self.configuration



end



def self.configure

yield(configuration)

end

end module Yourgemdef self.configuration @configuration ||= {}enddef self.configureyield(configuration)endend

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 will use Ruby’s built-in OpenStruct:

require 'ostruct'

def self.configuration



end



def self.configure

yield(configuration)

end

end module Yourgemdef self.configuration @configuration ||= OpenStruct.newenddef self.configureyield(configuration)endend

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.