Class: StatelyDB::KeyPath

Inherits:
Object
  • Object
show all
Defined in:
lib/key_path.rb

Overview

KeyPath is a helper class for constructing key paths.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeKeyPath

Returns a new instance of KeyPath.



6
7
8
9
# File 'lib/key_path.rb', line 6

def initialize
  super
  @path = []
end

Class Method Details

.to_key_id(value) ⇒ String

If the value is a binary string, encode it as a url-safe base64 string with padding removed.

Parameters:

Returns:

  • (String)


54
55
56
57
58
59
60
61
62
63
# File 'lib/key_path.rb', line 54

def self.to_key_id(value)
  if value.is_a?(StatelyDB::UUID)
    value.to_base64
  elsif value.is_a?(String) && value.encoding == Encoding::BINARY
    [value].pack("m0").tr("=", "").tr("+/", "-_")
  else
    # Any other value is just converted to a string
    value.to_s
  end
end

.with(namespace, identifier = nil) ⇒ KeyPath

Appends a new path segment.

Examples:

keypath = KeyPath.with("genres", "rock").with("artists", "the-beatles")

Parameters:

Returns:



46
47
48
# File 'lib/key_path.rb', line 46

def self.with(namespace, identifier = nil)
  new.with(namespace, identifier)
end

Instance Method Details

#inspectString

Returns:

  • (String)


30
31
32
# File 'lib/key_path.rb', line 30

def inspect
  to_str
end

#to_sString

Returns:

  • (String)


35
36
37
# File 'lib/key_path.rb', line 35

def to_s
  to_str
end

#to_strString

Returns:

  • (String)


25
26
27
# File 'lib/key_path.rb', line 25

def to_str
  "/".dup.concat(@path.join("/"))
end

#with(namespace, identifier = nil) ⇒ KeyPath

Appends a new path segment.

Parameters:

Returns:



15
16
17
18
19
20
21
22
# File 'lib/key_path.rb', line 15

def with(namespace, identifier = nil)
  if identifier.nil?
    @path << namespace
    return self
  end
  @path << "#{namespace}-#{self.class.to_key_id(identifier)}"
  self
end