Class: Hierarchy::IndexPath

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hierarchy/index_path.rb

Overview

An array of integers representing an ordered list of IDs. Duck-types an @Array@ in many ways.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, ...) ⇒ IndexPath

Returns A new instance.

Creates an index path from a list of integer IDs.

Parameters:

  • id (Fixnum)

    An integer ID.

Raises:

  • (ArgumentError)

    If an invalid ID is given.



23
24
25
26
# File 'lib/hierarchy/index_path.rb', line 23

def initialize(*indexes)
  raise ArgumentError, "IndexPath indexes must be integers" unless indexes.all? { |index| index.kind_of?(Fixnum) }
  @indexes = indexes
end

Class Method Details

.from_ltree(string) ⇒ IndexPath

Creates an index path from a PostgreSQL @LTREE@ column.

Parameters:

  • string (String)

    An @LTREE@ column value, such as “1.10.22”.

Returns:

  • (IndexPath)

    A corresponding index path.



33
34
35
# File 'lib/hierarchy/index_path.rb', line 33

def self.from_ltree(string)
  new(*(string.split('.').map(&:to_i)))
end

Instance Method Details

#<=>(other) ⇒ -1, ...

Defines a natural ordering of index paths. Paths with lower IDs at the same index level will come before those with higher IDs at that index level. Lower IDs at shallower index levels come before lower IDs at deeper index levels.

Parameters:

  • other (IndexPath)

    An index path to compare.

Returns:

  • (-1, 0, 1)

    -1 if this index path comes before the other one, 0 if they are identical, or 1 if this index path comes after the other one.

Raises:

  • (ArgumentError)

    If something other than an index path is given.



47
48
49
50
# File 'lib/hierarchy/index_path.rb', line 47

def <=>(other)
  raise ArgumentError, "Can't compare IndexPath and #{other.class.to_s}" unless other.kind_of?(IndexPath)
  indexes <=> other.send(:indexes)
end

#inspectObject



53
# File 'lib/hierarchy/index_path.rb', line 53

def inspect() "#<#{self.class.to_s} #{@indexes.inspect}>" end