Sha256: 270ac4ab17de7a9cafd8ece6f1b2341f1c117f28b953c1522f70f66cdc856b0a

Contents?: true

Size: 1 KB

Versions: 8

Compression:

Stored size: 1 KB

Contents

module Nyara
  class ConfigHash
    alias _aref []
    alias _aset []=

    # so you can find with chained keys
    def [] *keys
      h = self
      keys.each do |key|
        if h.has_key?(key)
          if h.is_a?(ConfigHash)
            h = h._aref key
          else
            h = h[key]
          end
        else
          return nil # todo default value?
        end
      end
      h
    end

    # so you can write:
    # config['a', 'very', 'deep', 'key'] = 'value
    def []= *keys, last_key, value
      h = self
      keys.each do |key|
        if h.has_key?(key)
          if h.is_a?(ConfigHash)
            h = h._aref key
          else
            h = h[key]
          end
        else
          new_h = ConfigHash.new
          if h.is_a?(ConfigHash)
            h._aset key, new_h
          else
            h[key] = new_h
          end
          h = new_h
        end
      end
      if h.is_a?(ConfigHash)
        h._aset last_key, value
      else
        h[last_key] = value
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
nyara-0.0.1.pre.8 lib/nyara/hashes/config_hash.rb
nyara-0.0.1.pre.6 lib/nyara/hashes/config_hash.rb
nyara-0.0.1.pre.5 lib/nyara/hashes/config_hash.rb
nyara-0.0.1.pre.4 lib/nyara/hashes/config_hash.rb
nyara-0.0.1.pre.3 lib/nyara/hashes/config_hash.rb
nyara-0.0.1.pre.2 lib/nyara/config_hash.rb
nyara-0.0.1.pre.1 lib/nyara/config_hash.rb
nyara-0.0.1.pre lib/nyara/config_hash.rb