Class: Hashcraft::Generic::Dictionary

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/hashcraft/generic/dictionary.rb

Overview

Dictionary structure defining how we want to organize objects. Basically a type-insensitive hash where each key is the object’s value for the specified key. All keys are #to_s evaluated in order to achieve the type-insensitivity.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key: :key) ⇒ Dictionary

Returns a new instance of Dictionary.

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
# File 'lib/hashcraft/generic/dictionary.rb', line 22

def initialize(key: :key)
  raise ArgumentError, 'key is required' if key.to_s.empty?

  @key = key
  @map = {}

  freeze
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



18
19
20
# File 'lib/hashcraft/generic/dictionary.rb', line 18

def key
  @key
end

#mapObject (readonly)

Returns the value of attribute map.



18
19
20
# File 'lib/hashcraft/generic/dictionary.rb', line 18

def map
  @map
end

Instance Method Details

#add(object) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/hashcraft/generic/dictionary.rb', line 41

def add(object)
  object_key = object.send(key)

  @map[object_key] = object

  self
end

#each(&block) ⇒ Object



31
32
33
34
35
# File 'lib/hashcraft/generic/dictionary.rb', line 31

def each(&block)
  return enum_for(:each) unless block_given?

  values.each(&block)
end

#find(key) ⇒ Object



37
38
39
# File 'lib/hashcraft/generic/dictionary.rb', line 37

def find(key)
  @map[key.to_s]
end

#merge!(other) ⇒ Object



49
50
51
52
53
# File 'lib/hashcraft/generic/dictionary.rb', line 49

def merge!(other)
  map.merge!(other.map)

  self
end