Module: Rubocop::Cop::Util

Included in:
Style::ClassLength
Defined in:
lib/rubocop/cop/util.rb

Overview

This module contains a collection of useful utility methods.

Class Method Summary collapse

Class Method Details

.block_length(block_node) ⇒ Object



22
23
24
# File 'lib/rubocop/cop/util.rb', line 22

def block_length(block_node)
  block_node.loc.end.line - block_node.loc.begin.line
end

.comment_line?(line_source) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/rubocop/cop/util.rb', line 38

def comment_line?(line_source)
  line_source =~ /^\s*#/
end

.const_name(node) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/rubocop/cop/util.rb', line 55

def const_name(node)
  return nil if node.nil? || node.type != :const

  const_names = []
  const_node = node

  loop do
    namespace_node, name = *const_node
    const_names << name
    break unless namespace_node
    break unless namespace_node.is_a?(Parser::AST::Node)
    break if namespace_node.type == :cbase
    const_node = namespace_node
  end

  const_names.reverse.join('::')
end

.line_range(arg) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rubocop/cop/util.rb', line 42

def line_range(arg)
  source_range = case arg
                 when Parser::Source::Range
                   arg
                 when Parser::AST::Node
                   arg.loc.expression
                 else
                   fail ArgumentError, "Invalid argument #{arg}"
                 end

  source_range.begin.line..source_range.end.line
end

.source_length(source, count_comments = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rubocop/cop/util.rb', line 26

def source_length(source, count_comments = nil)
  lines = source.lines.to_a[1...-1]

  return 0 unless lines

  lines.reject!(&:blank?)

  lines.reject! { |line| comment_line?(line) } unless count_comments

  lines.size
end

.strip_quotes(str) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rubocop/cop/util.rb', line 9

def strip_quotes(str)
  if str[0] == '"' || str[0] == "'"
    str[0] = ''
    str[-1] = ''
  else
    # we're dealing with %q or %Q
    str[0, 3] = ''
    str[-1] = ''
  end

  str
end