Class: Findyml::FileExtractor

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ FileExtractor

Returns a new instance of FileExtractor.



80
81
82
83
84
# File 'lib/findyml.rb', line 80

def initialize(file)
  @file = File.expand_path(file)
  @yaml = YAML.parse_file(@file)
  @anchors = {}
end

Class Method Details

.call(file, &block) ⇒ Object



76
77
78
# File 'lib/findyml.rb', line 76

def self.call(file, &block)
  new(file).extract(&block)
end

Instance Method Details

#construct_nodes(current_node = yaml) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/findyml.rb', line 103

def construct_nodes(current_node=yaml)
  nodes = case current_node
  when Psych::Nodes::Document
    return construct_nodes(current_node.children.first)
  when Psych::Nodes::Mapping
    current_node
      .children
      .each_slice(2)
      .each_with_object({}) { |(key, node), h|
        if key.is_a?(Psych::Nodes::Scalar) && key.value == '<<'
          h.merge!(construct_nodes(node).first)
        else
          key_node = KeyNode.new(key)
          h.delete(key_node)
          h[key_node] = construct_nodes(node)
        end
      }
  when Psych::Nodes::Sequence
    current_node
      .children
      .each_with_index
      .map { |node, index| [IndexNode.new(node, index), construct_nodes(node)] }
  when Psych::Nodes::Scalar
    nil
  when Psych::Nodes::Alias
    a_nodes, anchor = @anchors[current_node.anchor]
    return [a_nodes.transform_values { |(a, b, c)| [a, b, [*c, current_node]] }, anchor]
  end

  case current_node
  when Psych::Nodes::Mapping, Psych::Nodes::Sequence, Psych::Nodes::Scalar
    @anchors[current_node.anchor] = [nodes, current_node, []] if current_node.anchor
  end

  [nodes, current_node, []]
end

#extract(&block) ⇒ Object



86
87
88
89
90
91
92
# File 'lib/findyml.rb', line 86

def extract(&block)
  all_nodes = @yaml.children.map { construct_nodes(_1) }

  all_nodes.each do |nodes, _|
    extract_nodes(nodes, &block)
  end
end

#extract_nodes(nodes, path = [], alias_path = [], &block) ⇒ Object



94
95
96
97
98
99
100
101
# File 'lib/findyml.rb', line 94

def extract_nodes(nodes, path=[], alias_path=[], &block)
  nodes.each do |key_node, (children, yaml_node, alias_node)|
    new_path = [*path, key_node.to_s]
    new_alias_path = [*alias_path, *alias_node]
    yield Key.new(@file, key_node.node, new_path, children.nil?, new_alias_path)
    extract_nodes(children, new_path, new_alias_path, &block) if children
  end
end

#inspectObject



144
145
146
# File 'lib/findyml.rb', line 144

def inspect
  "#<Findyml::FileExtractor @file=#{@file.inspect}>"
end

#to_sObject



140
141
142
# File 'lib/findyml.rb', line 140

def to_s
  "FileExtractor(#{@file})"
end