Class: KeyPath::Path

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

Instance Method Summary collapse

Constructor Details

#initialize(path = '') ⇒ Path

Returns a new instance of Path.



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

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

Instance Method Details

#inspectObject



55
56
57
# File 'lib/key_path/path.rb', line 55

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

#parentObject



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

def parent
  s = self.to_a
  s.pop

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

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

#to_aObject



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

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

#to_collectionObject



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

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

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

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

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

  collection
end

#to_sObject



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

def to_s
  @path
end