Sha256: a2a94529254b22d0b9c085a9aeb64fc7f9d635911b9c0a1cb64f38faf24bf721

Contents?: true

Size: 805 Bytes

Versions: 3

Compression:

Stored size: 805 Bytes

Contents

module Labelizer
  class Container
    include Enumerable

    def initialize(keys,&block)
      case keys
      when Hash
        @keys = keys.keys
        @values = keys.values
        @map = keys.invert
      else
        @keys = keys
        @values = []
        @map = {}
      end
      @hash = Hash.new(&block)

      normalized_keys = @keys
      self.singleton_class.class_eval do
        normalized_keys.each do |key|
          define_method key do
            @hash[key]
          end
        end
      end
    end

    def [](key)
      return @hash[key] if @keys.include?(key)
      return @hash[@map[key]] if @values.include?(key)
      raise KeyError, "key: #{key.inspect} not found"
    end

    def each
      @keys.each do |key|
        yield key, @hash[key]
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
labelizer-0.1.0 lib/labelizer/container.rb
labelizer-0.0.5 lib/labelizer/container.rb
labelizer-0.0.4 lib/labelizer/container.rb