Configuration

Posts tagged with "Configuration."
  • 25

    JUN
    2008

    The One Method Config

    I've used this technique a couple of times now for dirt-simple configurations. The idea is to provide a trivial way to read and write configuration values with just a single method. Let me show you what I mean:

    module Configurable
      module_function
    
      def config(new_config = nil)
        if new_config.nil?
          @config ||= { }
        else
          config.merge!(new_config)
        end
      end
    end
    
    include Configurable
    
    config                    # => {}
    
    config :a => 1, :b => 2
    config                    # => {:a=>1, :b=>2}
    config[:a]                # => 1
    
    config :a => -1, :c => 3
    config                    # => {:a=>-1, :b=>2, :c=>3}
    
    config.clear
    config                    # => {}
    

    There's no deep magic here, obviously. The method has two function: read and write for the configuration. Read is handled with what I like refer to as Ruby's "caching operator" (||=). The first time that line is triggered, it will cache an empty Hash in the variable. Thereafter, the same call is just a cache hit to get the same Hash back.

    Read moreā€¦