Class: KeyPath::Path

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

Overview

The class representing a Path in a collection object.

Instance Method Summary collapse

Constructor Details

#initialize(path = '') ⇒ Path

Returns a new instance of Path.



4
5
6
# File 'lib/key_path/path.rb', line 4

def initialize(path = '')
  @path = path
end

Instance Method Details

#inspectObject



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

def inspect
  "#<#{self.class.name}:#{object_id} path=#{@path}>"
end

#parentObject



8
9
10
11
12
13
14
15
16
17
# File 'lib/key_path/path.rb', line 8

def parent
  s = to_a
  s.pop

  # there's no parent if it's empty
  return nil if s == []

  # otherwise, join them back together and pass back a path
  s.join('.').to_keypath
end

#to_aObject



23
24
25
# File 'lib/key_path/path.rb', line 23

def to_a
  @path.split('.')
end

#to_collectionObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/key_path/path.rb', line 27

def to_collection
  collection = {}
  s = to_a
  depth = ''

  s.each do |e|
    # assemble the key
    if e.is_number?
      key = "#{e}"
    else
      key = ":#{e}"
    end
    depth << "[#{key}]"

    # figure out the correct type to push
    type = {}
    type = [] if e.is_plural?

    # evaluate this stage
    eval "collection#{depth} = #{type}"
  end

  collection
end

#to_sObject



19
20
21
# File 'lib/key_path/path.rb', line 19

def to_s
  @path
end