Class: Labelizer::Container

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/labelizer/container.rb

Instance Method Summary collapse

Constructor Details

#initialize(keys, accept_array_key: false, &block) ⇒ Container

Returns a new instance of Container.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/labelizer/container.rb', line 5

def initialize(keys, accept_array_key: false, &block)
  @data = {
    is_accept_array_key: accept_array_key,
  }

  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|
      if key.is_a?(Symbol) || key.is_a?(String)
        define_method key do
          @hash[key]
        end
      end
    end
  end
end

Instance Method Details

#[](key) ⇒ Object

Raises:

  • (KeyError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/labelizer/container.rb', line 34

def [](key)
  return @hash[key] if @keys.include?(key)
  return @hash[@map[key]] if @values.include?(key)

  if @data[:is_accept_array_key]
    if key.respond_to?(:each)
      if key.all?{|k| @keys.include?(k)}
        return @hash[key]
      end
      if key.all?{|k| @values.include?(k)}
        return @hash[key.map{|k| @map[k]}]
      end
    end
  end

  raise KeyError, "key: #{key.inspect} not found"
end

#eachObject



58
59
60
61
62
# File 'lib/labelizer/container.rb', line 58

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

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/labelizer/container.rb', line 51

def has_key?(key)
  @keys.include?(key) || @values.include?(key)
end

#sizeObject



54
55
56
# File 'lib/labelizer/container.rb', line 54

def size
  @keys.size
end