Class: Dehenzify::Extractor

Inherits:
Parser::TreeRewriter
  • Object
show all
Defined in:
lib/dehenzify/extractor.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.empty_node?(node) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
# File 'lib/dehenzify/extractor.rb', line 15

def self.empty_node?(node)
  node.type == :module &&
    namespace_module?(node) &&
      node.children.select { |child| child&.type == :module }.all? { |child| empty_node?(child) }
end

.namespace_module?(node) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
11
12
13
# File 'lib/dehenzify/extractor.rb', line 3

def self.namespace_module?(node)
  last_child = node.children.last
  children =
    if last_child&.type == :begin
      last_child.children
    else
      node.children[1..-1]
    end

  (children.compact.map(&:type) - [:class, :module]).none?
end

Instance Method Details

#extract(file_path, code: nil, source_type: nil, base_dir: nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dehenzify/extractor.rb', line 34

def extract(file_path, code: nil, source_type: nil, base_dir: nil)
  @root_dir = (base_dir || Pathname.new(File.dirname(file_path))).join('../')
  @file_path = file_path.to_s
  @source_type = source_type
  @modules = []
  @extracted_sources = []

  code ||= File.read(file_path)
  ast = Parser::CurrentRuby.parse(code)

  buffer = Parser::Source::Buffer.new('')
  buffer.source = code
  new_source = rewrite(buffer, ast).gsub(/\n^\s*\n/, "\n\n")

  @extracted_sources << Dehenzify::ExtractedSource.new(@file_path, new_source)
  @extracted_sources
end

#on_class(node) ⇒ Object



29
30
31
32
# File 'lib/dehenzify/extractor.rb', line 29

def on_class(node)
  extract_source(node) if @source_type.nil? || @source_type == :class
  # Don't descend into classes
end

#on_module(node) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/dehenzify/extractor.rb', line 21

def on_module(node)
  @modules << node.children.first.loc.expression.source
  super
  @modules.pop

  extract_source(node) if !Dehenzify::Extractor.namespace_module?(node) && (@source_type.nil? || @source_type == :module)
end