Class: Any2Tmx::Traversable

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ Traversable

Returns a new instance of Traversable.



5
6
7
# File 'lib/any2tmx/traversable.rb', line 5

def initialize(collection)
  @collection = collection
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



3
4
5
# File 'lib/any2tmx/traversable.rb', line 3

def collection
  @collection
end

Instance Method Details

#dig(path) ⇒ Object



44
45
46
47
# File 'lib/any2tmx/traversable.rb', line 44

def dig(path)
  return collection if path.empty?
  dig_each(path) {}
end

#dig_each(path) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/any2tmx/traversable.rb', line 23

def dig_each(path)
  if block_given?
    path.inject(:start) do |ret, seg|
      if ret == :start
        yield collection, seg
        collection[seg]
      elsif ret
        if seg.is_a?(Numeric) && ret.is_a?(Array)
          yield ret, seg
          ret[seg]  # array index case
        elsif ret.is_a?(Hash)
          yield ret, seg
          ret[seg]  # hash key case
        end
      end
    end
  else
    to_enum(__method__, path)
  end
end

#each_entry(&block) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/any2tmx/traversable.rb', line 9

def each_entry(&block)
  if block_given?
    each_entry_helper(collection, [], nil) do |entry, path, last_key|
      yield entry, path + [last_key]
    end
  else
    to_enum(__method__)
  end
end

#sizeObject



19
20
21
# File 'lib/any2tmx/traversable.rb', line 19

def size
  each_entry.inject(0) { |ret, _| ret + 1 }
end

#stringify_keysObject



74
75
76
77
78
# File 'lib/any2tmx/traversable.rb', line 74

def stringify_keys
  transform do |obj, key, value|
    obj[stringify(key)] = value
  end
end

#transformObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/any2tmx/traversable.rb', line 49

def transform
  if block_given?
    self.class.new(make_empty(sym_from(collection))).tap do |copy|
      each_entry_helper(collection, [], nil) do |entry, path, last_key|
        dig_each(path).inject(copy.collection) do |copy_obj, (obj, key)|
          copy_obj[key] ||= make_empty(sym_from(obj[key]))
          copy_obj[key]
        end

        yield copy.dig(path), last_key, entry
      end
    end
  else
    to_enum(__method__)
  end
end

#zip(other_traversable) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/any2tmx/traversable.rb', line 66

def zip(other_traversable)
  each_entry.each_with_object({}) do |(entry, path), ret|
    other_entry = other_traversable.dig(path)
    ret[entry] = other_entry if other_entry
    yield if block_given? && other_entry
  end
end