class Hashematics::Key

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.

Constants

SEPARATOR

Attributes

parts[R]
value[R]

Public Class Methods

default(parts = [])
Alias for: get
get(parts = []) click to toggle source

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.

# File lib/hashematics/key.rb, line 21
def get(parts = [])
  return parts if parts.is_a?(self)

  keys[parts] ||= new(parts)
end
Also aliased as: default
new(parts = []) click to toggle source
# File lib/hashematics/key.rb, line 43
def initialize(parts = [])
  @parts = Array(parts)
  @value = make_value

  freeze
end

Private Class Methods

keys() click to toggle source
# File lib/hashematics/key.rb, line 30
def keys
  @keys ||= {}
end

Public Instance Methods

==(other) click to toggle source
# File lib/hashematics/key.rb, line 62
def ==(other)
  eql?(other)
end
eql?(other) click to toggle source

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.

# 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
hash() click to toggle source
# File lib/hashematics/key.rb, line 66
def hash
  value.hash
end

Private Instance Methods

make_value() click to toggle source
# File lib/hashematics/key.rb, line 72
def make_value
  parts.map(&:to_s).join(SEPARATOR)
end