Configuration pattern in Ruby

Sometimes you need to add flexibility to your code and this pattern is a simple and clear way to accomplish this.It is widely used in gems also.

This is how it’s used:

Zuper.configure do |config|
  config.name = 'ACME'
  config.platform = 'Unix'
end

You can then access the values:

Zuper.configuration.name
Zuper.configuration.platform

And this is the implementation:

module Zuper
  class Configuration
    attr_accessor :name, :platform
  end

  class << self
    attr_writer :configuration
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.configure
    yield configuration
  end
end
Advertisements

One thought on “Configuration pattern in Ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s