Sha256: 61e4923e309de862f3dda2600696772550c716fcebb9adf3d5d05da2cb500f04

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

class Hash
  class Normalized < Hash

    def self.subclass(&block)
      Class.new(self) do
        define_method :initialize do |hash={}|
          super hash, &block
        end
      end
    end

    def initialize(hash={}, &block)
      @normalization_block = block
      update hash
    end

    def [](key)
      super normalize_key(key)
    end

    def []=(key, value)
      super normalize_key(key), normalize_value(value)
    end
    alias_method :store, :[]=

    def delete(key)
      super normalize_key(key)
    end

    def update(hash)
      hash.each do |key, value|
        store normalize_key(key), normalize_value(value)
      end
      self
    end
    alias_method :merge!, :update

    def merge(hash)
      dup.update hash
    end

    def key?(key)
      super normalize_key(key)
    end
    alias_method :include?, :key?
    alias_method :has_key?, :key?
    alias_method :member?, :key?

    def fetch(key, *args, &block)
      super normalize_key(key), *args, &block
    end

    private

    def normalize_key(key)
      @normalization_block.call key
    end

    def normalize_value(value)
      if value.kind_of? Hash
        self.class.new value
      elsif value.kind_of? Array
        value.map { |v| normalize_value v }
      else
        value
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hash_ext-0.2.1 lib/hash_ext/normalized.rb
hash_ext-0.2.0 lib/hash_ext/normalized.rb