Class: Hashematics::Key

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/hashematics/key.rb

Overview

A Key is a unique identifier and can be used for hash keys, comparison, etc. Essentially it is a joined and hashed list of strings.

Direct Known Subclasses

Id

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parts = []) ⇒ Key

Returns a new instance of Key.



43
44
45
46
47
48
# File 'lib/hashematics/key.rb', line 43

def initialize(parts = [])
  @parts = Array(parts)
  @value = make_value

  freeze
end

Instance Attribute Details

#partsObject (readonly)

Returns the value of attribute parts.



41
42
43
# File 'lib/hashematics/key.rb', line 41

def parts
  @parts
end

#valueObject (readonly)

Returns the value of attribute value.



41
42
43
# File 'lib/hashematics/key.rb', line 41

def value
  @value
end

Class Method Details

.get(parts = []) ⇒ Object Also known as: default

This class-level method allows for the caching/memoization of Key objects already allocated. Since Key objects will have such a high instantiation count with the potential of a lof of re-use, it makes sense to try to be a bit more memory-optimized here.



21
22
23
24
25
# File 'lib/hashematics/key.rb', line 21

def get(parts = [])
  return parts if parts.is_a?(self)

  keys[parts] ||= new(parts)
end

Instance Method Details

#==(other) ⇒ Object



62
63
64
# File 'lib/hashematics/key.rb', line 62

def ==(other)
  eql?(other)
end

#eql?(other) ⇒ Boolean

We can compare a Key object to a non-Key object since its constructor is rather pliable. This means we can do things like this:

  • Key.make([‘id’, :name]) == [‘id’, ‘name’]

  • Key.make(:id) == ‘id’

  • Key.make() == :id

Those are all equivalent and should return true.

Returns:

  • (Boolean)


56
57
58
59
60
# File 'lib/hashematics/key.rb', line 56

def eql?(other)
  return eql?(self.class.get(other)) unless other.is_a?(self.class)

  value == other.value
end

#hashObject



66
67
68
# File 'lib/hashematics/key.rb', line 66

def hash
  value.hash
end