Class: McCabe::Analyzer
- Inherits:
-
Object
- Object
- McCabe::Analyzer
- Defined in:
- lib/mccabe/analyzer.rb,
lib/mccabe/analyzer/method_info.rb
Defined Under Namespace
Classes: MethodInfo
Constant Summary collapse
- BRANCH_TYPES =
[:if, :while, :until, :for, :when, :and, :or]
- ENUMERABLE_METHODS =
Enumerable.instance_methods + [:each]
Class Method Summary collapse
- .analyze(file) ⇒ Object
- .block_complexity(block_node) ⇒ Object
- .complexity(ast) ⇒ Object
- .send_complexity(send_node) ⇒ Object
Class Method Details
.analyze(file) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/mccabe/analyzer.rb', line 9 def self.analyze(file) ast = McCabe::Parser.parse(File.read(file)) McCabe::Parser.collect_methods(ast).map do |name, method_ast| MethodInfo.new( name, complexity(method_ast[:body]), file, method_ast[:line] ) end end |
.block_complexity(block_node) ⇒ Object
37 38 39 40 41 |
# File 'lib/mccabe/analyzer.rb', line 37 def self.block_complexity(block_node) sent_method = block_node.children[0] sent_method.children.length == 2 && ENUMERABLE_METHODS.include?(sent_method.children[1]) ? 1 : 0 end |
.complexity(ast) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/mccabe/analyzer.rb', line 21 def self.complexity(ast) nodes, complexity = [ast], 0 until nodes.empty? node = nodes.shift || next if BRANCH_TYPES.include?(node.type) complexity += 1 elsif node.type == :block complexity += block_complexity node elsif node.type == :send complexity += send_complexity node end nodes += node.children.select { |child| child.is_a? ::Parser::AST::Node } end complexity end |
.send_complexity(send_node) ⇒ Object
43 44 45 46 47 |
# File 'lib/mccabe/analyzer.rb', line 43 def self.send_complexity(send_node) send_node.children.length >= 3 && send_node.children[2].type == :block_pass && ENUMERABLE_METHODS.include?(send_node.children[1]) ? 1 : 0 end |