Class: KeyTree::Path

Inherits:
Array
  • Object
show all
Defined in:
lib/key_tree/path.rb

Overview

Representation of the key path to a value in a key tree

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_path = nil) ⇒ Path

KeyTree::Path.new(key_or_path)

Make a new key path from a dot separated string, single symbol, or array of strings or symbols.

Example:

KeyTree::Path.new("a.b.c")
=> ["a", "b", "c"]


33
34
35
36
37
38
39
40
41
42
# File 'lib/key_tree/path.rb', line 33

def initialize(key_path = nil)
  case key_path
  when NilClass
    nil
  when Array
    concat(key_path.map(&:to_sym))
  else
    initialize(key_path.to_key_path)
  end
end

Class Method Details

.[](*key_paths) ⇒ Object

KeyTree::Path[key_or_path, …]

Make a new key path from one or more keys or paths



17
18
19
20
21
# File 'lib/key_tree/path.rb', line 17

def self.[](*key_paths)
  key_paths.reduce(Path.new) do |result, key_path|
    result << key_path.to_key_path
  end
end

Instance Method Details

#+(other) ⇒ Object



60
61
62
# File 'lib/key_tree/path.rb', line 60

def +(other)
  dup.concat(other.to_key_path)
end

#-(other) ⇒ Object

Returns a key path without the leading prefix

:call-seq:

Path - other => Path

Raises:

  • (KeyError)


68
69
70
71
72
# File 'lib/key_tree/path.rb', line 68

def -(other)
  other = other.to_key_path
  raise KeyError unless prefix?(other)
  super(other.length)
end

#<<(other) ⇒ Object



56
57
58
# File 'lib/key_tree/path.rb', line 56

def <<(other)
  concat(other.to_key_path)
end

#conflict?(other) ⇒ Boolean

Would other conflict?

Returns:

  • (Boolean)


88
89
90
# File 'lib/key_tree/path.rb', line 88

def conflict?(other)
  prefix?(other) || other.prefix?(self) if self != other
end

#inspectObject



52
53
54
# File 'lib/key_tree/path.rb', line 52

def inspect
  %("#{self}")
end

#prefix?(other) ⇒ Boolean Also known as: ===

Is other a prefix?

:call-seq:

prefix?(other) => boolean

Returns:

  • (Boolean)


78
79
80
81
82
83
# File 'lib/key_tree/path.rb', line 78

def prefix?(other)
  other = other.to_key_path
  return false if other.length > length
  key_enum = each
  other.all? { |other_key| key_enum.next == other_key }
end

#to_key_pathObject



44
45
46
# File 'lib/key_tree/path.rb', line 44

def to_key_path
  self
end

#to_sObject



48
49
50
# File 'lib/key_tree/path.rb', line 48

def to_s
  join('.')
end